use C program A pentagonal number is defined as n(3n–1)/2 for n = 1, 2, . . ., and so on. Therefore, the first few numbers are 1, 5, 12, 22, . . . . Write a method with the following header that returns a pentagonal number: int getPentagonalNumber(int n) Write a test program that uses this method to display the first 100 pentagonal numbers(%10d for width) with 10 numbers on each line.
时间: 2024-02-28 21:53:14 浏览: 441
Certainly! Here's a C program that defines a `getPentagonalNumber` function that computes the nth pentagonal number, and a `main` function that uses this function to display the first 100 pentagonal numbers with 10 numbers on each line:
```
#include <stdio.h>
int getPentagonalNumber(int n) {
return n * (3 * n - 1) / 2;
}
int main() {
int i, n;
for (i = 1; i <= 100; i++) {
n = getPentagonalNumber(i);
printf("%10d", n);
if (i % 10 == 0) {
printf("\n");
}
}
return 0;
}
```
The `getPentagonalNumber` function takes an integer `n` as input, and returns the nth pentagonal number using the formula n(3n–1)/2. The `main` function then calls this function to compute the first 100 pentagonal numbers, and prints them out using `%10d` to format each number with a width of 10 characters. If the current number being printed is a multiple of 10 (i.e., `i % 10 == 0`), then we print a newline character to start a new line.
阅读全文