数字不断求和,但不会停止求和

Numbers keep summing but does not stop summing

本文关键字:求和 数字      更新时间:2023-10-16

>我做了一个程序,允许用户输入他们想要求和的整数数量,我能够得到它,但是当用户再次访问时,它会继续添加到以前的总和时应该重新启动并添加新整数。

#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;
}