数字不断求和,但不会停止求和
Numbers keep summing but does not stop summing
>我做了一个程序,允许用户输入他们想要求和的整数数量,我能够得到它,但是当用户再次访问时,它会继续添加到以前的总和时应该重新启动并添加新整数。
#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()
// =================
在 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? ";
...
在 while 循环开始时:
total = 0;
下面是代码的更短、更改进的版本。
int main()
{
char ans;
do {
int n, sum = 0;
std::cout << "Enter the number of numbersn";
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 << "Byen";
return 0;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 如何使用循环对所有数字求和?
- 循环中的线程 Runnin 用于对 c++ 中的数字求和
- 找到所有与自己求和的数字X的快速方法,去掉一个数字得到N
- 使用特征类对向量中的某些数字求和
- C++对以前打印的列表中的数字求和
- 一个简单的程序,对数字进行计数和求和.我怎样才能让它工作
- C++简介:将字符串从文件行中的数字中分离出来,并对这些数字求和
- 求和数字递归C++
- 对大数字求和
- C++,要求用户输入一组数字求和(未知的输入数量),但是数字不会加起来
- 求和巨大的数字
- 如何在c++中对数组的一行中的数字求和
- 编写一个函数从文件中读取数字并求和
- 将特定数字求和以获得100的不同方法
- 数字不断求和,但不会停止求和