// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
int num2;
int sum;
int i = 0;
cout << "enter a number: ";
cin >> num;
cout << "enter another number: ";
cin >> num2;
sum = num + num2;
for(i = 0 ; i <= sum ; i++)
{
cout << "loop iteration: " << sum << endl;
}
return 0;
}
这是我到目前为止的代码。现在它工作正常它计算总和,但是,总和是3,它将打印:
loop iteration: 3
loop iteration: 3
loop iteration: 3
但是我想把它打印出来:
loop iteration: 3
loop iteration: 2
loop iteration: 1
我不确定问题是否在我的陈述内,我想我的订单可能有错。
答案 0 :(得分:1)
问题是您反复打印相同的sum
而不是递减sum
。您可以使用sum
运算符在for
循环内递减sum--
,也可以修改循环,如下所示。
for(i = sum ; i >= 1 ; i--)
{
cout << "loop iteration: " << i << endl;
}
答案 1 :(得分:-1)
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
int num2;
int sum;
int i = 0;
cout << "enter a number: ";
cin >> num;
cout << "enter another number: ";
cin >> num2;
sum = num + num2;
while(sum != 0){
cout << "loop iteration: " << sum << endl;
sum--;
}
return 0;
}