我创建了一个程序,允许用户输入他们想要求和的总数,但我能够得到它但是当用户再次运行时,它会在应该重新启动时添加到前一个总和并添加新的整数
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// ================
int main() {
// Declared Variables
int num;
int sum;
int total = 0;
char ans = 'y';
// ===========
using namespace std;
// While loop which allows user to go again.
while (ans == 'y' || ans == 'Y')
{
// Input for adding any number of integers
cout << "How many integer values would you like to sum? ";
cin >> num;
cout << endl;
// =========
// For Loop allows to add integers
for (int i = 0; i < num; i++)
{
cout << "Enter an integer value: ";
cin >> sum;
total += sum;
} // End for loop
// ==============
// Prints out the sum of the numbers
cout << "The sum is " << total << endl;
cout << endl;
// Asks the user if they want to go again
cout << "Would you like to go again (y/n)? ";
cin >> ans;
cout << endl;
if (ans != 'y')
{
cout << "Bye..." << endl;
}// End If statement
// ================
}// End while loop
// ==============
cout << endl;
return 0;
} // Function main()
// =================
答案 0 :(得分:4)
在while循环中移动此行:
int total = 0;
即:
while (ans == 'y' || ans == 'Y')
{
int total = 0;
// Input for adding any number of integers
cout << "How many integer values would you like to sum? ";
...
答案 1 :(得分:0)
在你的while循环开始时:
total = 0;
这是一个更短,更改的代码版本。
int main()
{
char ans;
do {
int n, sum = 0;
std::cout << "Enter the number of numbers\n";
std::cin >> n;
while (--n >= 0) {
int x;
std::cout << "Number? ";
std::cin >> x;
sum += x;
}
std::cout << "Sum is " << sum << "\nGo again?(y/n)\n";
std::cin >> ans;
} while (ans == 'y' || ans == 'Y');
std::cout << "Bye\n";
return 0;
}