执行后如何使变量不保留其值?

时间:2019-01-23 19:12:32

标签: visual-c++

我正在为学校项目创建菜单,并且该菜单应该连续运行,直到用户选择退出选项,但是问题是,如果用户在另一个选项之后选择一个选项,则会添加前一个选项的值到目前的,并继续重复。它带出正确值的唯一方法是首先运行该选项。所以我想知道是否有一种方法可以使变量不保留其谷值

int main()
{
int choice, sum = 0, n, num, count = 0, a;


do {
    cout << "1. Sum of first 10 natural numbers" << endl;
    cout << "2. Sum of n natural numbers" << endl;
    cout << "3. Prime number check" << endl;
    cout << "4. Exit" << endl;
    cout << "Enter your choice" << endl;
    cin >> choice;


    switch (choice)
    {
        case 1: {
            for (int i = 1; i <= 10; ++i) {
                sum += i;
            }
            cout << "Sum of first 10 natural numbers =" << sum << endl;
            break;
        }

        case 2: {
                cout << "Enter a positive integer: ";
            cin >> n;
            for (int i = 1; i <= n; ++i) {
                sum += i;
            }
            cout << "Sum of first " << n << "natural numbers =" << sum << endl;
            break;
        }
        case 3: {
            cout << "Enter number to be checked : ";
            cin >> num;
            if (num == 0 || num < 0) {
                cout << "\n" << num << " is not prime." << endl;
            }
            else {
                for (a = 2; a < num; a++)
                    if (num % a == 0)
                        count++;
            }
            if (count > 1)
                cout << "\n" << num << " is not prime." << endl;
            else
                cout << "\n" << num << " is prime." << endl;
            break;
        }
    }
} while (choice < 4);
}

因此,如果我选择选项2而我输入5,则代码会产生正确的答案,即15,但如果我再次选择选项2并输入5,它将产生30;如果我再次选择它,它将产生45。其他情况也一样。它将先前的结果添加到当前结果中。

1 个答案:

答案 0 :(得分:0)

在执行计算之前/之后,您不会将sum变量重置为零,因此它将继续累加。在您的switch语句之前尝试sum = 0。

cout << "Enter your choice" << endl;
cin >> choice;

sum = 0;

switch (choice)
{