为什么我的代码没有跟踪最小的数字? (C++原理与实践第4章演练)

问题描述 投票:0回答:1
#include "std_lib_facilities.h"


int main()
{
    // Variable declaration
    double smallest = 0;
    double largest = 0;
    double num = 0;
    double stop_char = 0;

    // User input and loop through it
    cout << "Please, introduce a number ('|' to exit) \n";
    while(cin >> num && stop_char != '|') {
        cout << num << "\n";
        if(num < smallest) {
            smallest = num;
            cout << "The smallest so far is: " << smallest << "\n";
        } else if(num > largest) {
            largest = num;
            cout << "The largest so far is: " << largest << "\n";
        }
    }
    cout << "You're leaving the program!";
}

我能够运行代码并跟踪迄今为止最大的数字,但由于某种原因无法跟踪最小的数字......

c++ while-loop max double min
1个回答
0
投票

变量

stop_char
实际上没有被使用并且是多余的。

书中有如何编写循环的示例。

您可以按以下方式编写 for 循环

for ( double temp; cin >> temp; )
{
    //...
}

或者像这样的 while 循环

double temp;
while ( cin >> temp )
{
    //...
}

还有这样写

我们使用输入操作 cin >> temp 作为 for 的条件 声明。

上面显示的 while 语句中使用了相同的条件。

如果正确读取值,则条件

cin >> temp
的值为
true
。否则其值为
false

字符

'|'
与任何其他不能用作 double 类型对象的输入的字符一样,用于终止输入和相应的循环。

double
类型的值可以为负值和正值。所以这些初始零值

double largest = 0;
double num = 0;

循环中没有意义。您需要在循环的第一次迭代中将它们设置为实际值。

程序可以通过以下方式查看例如:

#include "std_lib_facilities.h" int main() { // Variable declaration bool first_iteration = true; double smallest = 0; double largest = 0; // User input and loop through it cout << "Please, introduce a number ('|' to exit) \n"; double num; while ( cin >> num ) { cout << num << "\n"; if ( first_iteration || num < smallest) { first_iteration = false; smallest = num; cout << "The smallest so far is: " << smallest << "\n"; } if ( first_iteration || largest < num ) { first_iteration = false; largest = num; cout << "The largest so far is: " << largest << "\n"; } } cout << "You're leaving the program!"; }
    
© www.soinside.com 2019 - 2024. All rights reserved.