告诉计算机在打印答案后清除它

Tell computer to clear the answer after it is being printed

本文关键字:清除 答案 打印 计算机      更新时间:2023-10-16

程序旨在将从1到我输入的数字的所有数字平方并相加。如果我只输入一个数字,答案将是正确的,但如果我不停止它并重新打开我的程序,我输入的第二个数字的答案也将添加第一个数字的结果。我错过了什么?请帮忙。

#include<iostream>
using namespace std;
int main()
{
int inNum;
int loopCount = 1;
int count;
int sum = 0;
cout << "Enter a number greater than 0 (less than 1 to quit): " << endl;
cin >> inNum;
while ( inNum >= loopCount) {
    for (count=0 ; count <= inNum ; count++ ){
        sum = sum + count * count; 
    }
    cout << "The sum of the squares from 1 to " << inNum << " is " << sum << endl;
    cout << "Enter a number greater than 0 (less than 1 to quit): " << endl;
    cin >> inNum;
}
}

一个解决方案是将sum的声明移动到while块中

// int sum = 0;
while ( inNum >= loopCount) {
  int sum = 0; // <-- or just sum = 0; and keep the declaration outside the loop

另一个(如注释中所述)是在循环体的末尾重置sum