c ++ Sentinel循环,存储最小和最大数字

c++ Sentinel loop, store lowest and biggest number

这是我的程序:

#include <iostream>
using namespace std;

int main(){
    int num;
    int numtotal = 0;
    int numcount = 0;
    int big = 0;
    int low = 0;

    cout<<"enter number or 0 to exit"<<endl;
    cin>>num;
    while(num != 0){
        numtotal = numtotal + num;
        numcount++;
        big = num;
        low = num;

        cout<<"enter number or 0 to extit"<<endl;
        cin>>num;

        if(num < low){
            low = num;
        }
        else if(num > big){
            big = num;
        }
    }

    cout<<"total of numbers: "<<numtotal<<endl;
    cout<<"totoal of numbers entered: "<<numcount<<endl;
    cout<<"biggest number: "<<big<<endl;
    cout<<"lowest number: "<<low<<endl;
}

"low" 和 "big" 输出始终是用户输入的最后两个数字,例如:

( 5, 4, 3, 2)

biggest number: 2

lowest number: 0

我做错了什么?谢谢

你总是在你的循环中用当前数字覆盖 big 和 low..

这可以通过初始化 biglow 一次(在循环的一侧)来解决,如下所示:

#include <limits>
int big = std::numeric_limits<int>::min();
int low = std::numeric_limits<int>::max();

并将循环更改为

while(num != 0) {
    numtotal += num;
    numcount++;

    cout << "enter number or 0 to exit" << endl;
    cin >> num;

    if(num < low)
        low = num;
    // note that this isn't in the else branch anymore
    // to also work if num is the biggest and lowest number
    if(num > big)
        big = num;
}

您总是将它们设置在循环的顶部。尝试像这样将它们放在循环之外:

    cout<<"enter number or 0 to exit"<<endl;
    cin>>num;

    // move them here
    big = num;
    low = num;


    while(num != 0){
        numtotal = numtotal + num;
        numcount++;

        cout<<"enter number or 0 to extit"<<endl;
        cin>>num;

        if(num < low){
            low = num;
        } else if(num > big){
            big = num;
        }
    }

如果用户在 while 循环中输入 0 以达到您想要的结果,则无需将 biglow 设置为 num

否则,如果您不这样做,您的输出最小数字将始终是 0(如果用户只输入正数,我认为您不希望这样):

#include <iostream>
using namespace std;

int main() {
    int num;
    int total = 0;
    int count = 0;

    cout << "Enter number or 0 to exit" << endl;
    cin >> num;

    int biggest = num;
    int lowest = num;

    while (num != 0) {
        total += num;
        count++;
        cout << "Enter number or 0 to exit" << endl;
        cin >> num;
        if (num != 0) {
            if (num < lowest) {
                lowest = num;
            } else if (num > biggest) {
                biggest = num;
            }
        }
    }

    cout << "Total of numbers: " << total << endl;
    cout << "Amount of numbers entered: " << count << endl;
    cout << "Biggest number: " << biggest << endl;
    cout << "Lowest number: " << lowest << endl;

    return 0;
}

用法示例:

Enter number or 0 to exit
5
Enter number or 0 to exit
4
Enter number or 0 to exit
3
Enter number or 0 to exit
2
Enter number or 0 to exit
0
Total of numbers: 14
Amount of numbers entered: 4
Biggest number: 5
Lowest number: 2