我是新手,这是我上学的功课。该程序假设打印从1到5(而不是5到1),到目前为止,我只能使程序从5打印到1,任何对此的帮助将是值得赞赏的。 程序应该只使用while循环
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[])
{
//if statement to check only 2 argument can be passed
if (argc != 2)
{
cout << "ERROR!" << endl;
}
else
{
if (atoi(argv[1]) < 1) //if statement to check negative numbers
{
cout << "ERROR!"<< endl;
}
int temp = atoi(argv[1]); //convert the number inthe character argument to integer
int sum = 0; //variable declaration to find the sum passed in the while loop
//the while loop is used to print out the numbers entered in descending order
while (temp > 0)
{
cout << temp << endl; //output numbers in the iteration
sum = sum + temp; //sums the number of iteration
temp --; //counter, used to stop the while loop to avois an infinity loop
}
cout << "Sum is " << sum << endl;
}
return 0;
}
答案 0 :(得分:2)
使用for循环
for(int i=1;i<=temp;i++){
cout << i << endl; //output numbers in the iteration
sum = sum + i;
}
或像这样的while循环
int counter=1;
while (counter<=temp)
{
cout << counter << endl; //output numbers in the iteration
sum = sum + counter; //sums the number of iteration
counter ++; //counter, used to stop the while loop to avois an infinity loop
}