Stroustrup C ++ Book。如何跟踪while循环中哪个整数输入最小和最大?

时间:2016-08-09 04:28:45

标签: c++

我是C ++编程和一般编程的新手,当我遇到第4章第6章时,我正在阅读Stroustrup的编程原理和练习使用C ++第2版。

问题如下: 编写一个由while循环组成的程序,该循环读入两个int然后打印它们。 更改程序以写出较小的值和较大的值。 等等 现在改变循环的主体,使其每次只读取一个双精度。定义两个变量来跟踪哪个是最小的,哪个是你到目前为止看到的最大值。每个itme通过循环写出输入的vlue如果它是迄今为止最小的,写入目前为止最小的数字。如果它是迄今为止最大的,那么在该数字之后写入最大的。

基本上,我无法保持最小和最大值贯穿所有循环。因为,目前所发生的一切都是每次我输入两个数字时,它只显示哪个是我在程序中早先已经达到的最大/最小值。它不会保持最大/最小值,直到其中一个循环中的值更小/更大为止。

我希望我能够清楚地解释这种情况。我确定它只是一个非常简单的修复,我是编程的新手。 到目前为止,这是我的代码:

#include "../../../std_lib_facilities.h";

int main()
{
    double val1;
    double val2;
    double largest =0  ;
    double smallest= 0 ;
    double input = 0;

    char exit = ' ';

    while (exit != 'x') {
        cout << "Please enter two numbers.\n";
        cin >> val1 >> val2;
        cout << "The two values you have entered are: " << val1 << " and " << val2 << "\n";

        if (val1 < val2) {
            cout << "The smaller value is: " << val1 << ". The larger value is: " << val2 << ".\n";
            if (val2 - val1 <= .5)
                cout << "The numbers are almost equal.\n";
        }
        else if (val2 < val1) {
            cout << "The smaller value is: " << val2 << ". The larger value is: " << val1 << ".\n";
            if (val1 - val2 <= .5)
                cout << " The numbers are almost equal.\n";
        }
        else
            cout << "The two numbers " << val1 << " are equal!\n"; \

            if (val1 < smallest && val2>val1) {
                cout << val1 << " is the smallest so far.\n";
                smallest = val1;
            }
            else if (val2<smallest && val1>val2) {
                cout << val2 << " is the smallest so far.n";
                smallest = val2;
            }
            else {}


            if (val1 > largest && val2 < val1) {
                cout << val1 << " is the largest so far.\n";
                val1 = largest;
            }
            else if (val2 > largest && val1 < val2) {
                cout << val2 << " is the largest so far.\n";
                val2 = largest;
            }
            else {

            }

            cout << "If you would like to exit this program, please enter x. Otherwise, enter any other key to continue. \n";
            cin >> exit;
    }
}

1 个答案:

答案 0 :(得分:4)

您没有正确跟踪最大值。

            cout << val1 << " is the largest so far.\n";
            val1 = largest;  // Wrong

需要

            cout << val1 << " is the largest so far.\n";
            largest = val1;

            cout << val2 << " is the largest so far.\n";
            val2 = largest;  // Wrong

需要

            cout << val2 << " is the largest so far.\n";
            largest = val2;