我正在尝试编写一个计算前n个正奇数整数之和的程序.
我无法弄清楚如何将n合并到求和中.我已经有一个do / while循环来确保在赋值时得到正值.我知道我必须使用for循环,但我不确定我会怎么做.
Scanner input = new Scanner(System.in); // open input stream
String cleanUpStr; // clean kbd buffer
int n; // number
int sum; // sum of numbers
int cntr; // counter for loop
cleanUpStr = "nothing yet";
n = 0;
sum = 0;
cntr = 0;
//prompt user for the value of n
// use a loop to ensure a positive output
do
{
System.out.println("Enter the value of n");
n = input.nextInt();
cleanUpStr = input.nextLine();
// print error if n is invalid
if (n < 0)
{
System.out.println("Invalid n value of " + n + ", try again.");
} // end if
}while(n < 0);
for(cntr = 0; cntr < n; ++cntr)
{
} // end for
} // end main
例如:如果n = 5,那么这应该计算1 3 5 7 9.