gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:42:48 24 4
gpt4 key购买 nike

我是 C++ 编程的新手,只是一般编程,当我卡在第 4 章练习 6 时,我正在学习 Stroustrup 的编程原则和使用 C++ 第 2 版的实践。

问题是:编写一个包含 while 循环的程序,该循环读取两个 int,然后打印它们。改变程序写出较小的值,和较大的值。等等等等现在更改循环体,使其每次只读取一个 double。定义两个变量以跟踪您目前看到的最小值和最大值。每次循环都写出输入的 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;
}
}

最佳答案

您没有正确跟踪最大值。

            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;

关于c++ - Stroustrup C++ 书籍。如何跟踪 while 循环中哪个整数输入最小和最大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38842075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com