【发布时间】:2016-05-15 09:46:42
【问题描述】:
你能帮我解决简单的问题吗?我对 C++ 非常熟悉,并从 Bjarne Stroustrup 的“编程:使用 C++ 的原则和实践”一书中学习。我以前从未学过 C++,所以我不熟悉许多有用的特性。钻头说:
"6. 现在改变循环体,让它只读取一个双精度数 每次。定义两个变量来跟踪哪个是 最小的,这是您迄今为止看到的最大值。每个 通过循环的时间写出输入的值。如果是 迄今为止最小的,在数字后面写迄今为止最小的。如果是 迄今为止最大的,在数字后面写迄今为止最大的”
如果不使用矢量,我不知道如何正确执行此操作。这是我的代码:
#include "C:/std_lib_facilities.h"
int main()
{
double a, b,differ=0;
char c=' ';
cout << "Enter two values: \n";
while (c != '|' && cin >> a >> b )
{
if (a > b)
{
cout << "The smaller value is: "<< b << " and the larger value is: " << a << "\n \n";
differ = a - b;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else if (a < b)
{
cout << "The smaller value is: " << a << " and the larger value is: " << b << "\n \n";
differ = b - a;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else
{
cout << "These values are equal!\n";
}
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
这里是前面的步骤,这些我已经用上面的代码解决了:
- 编写一个由 while 循环组成的程序,该循环(每次围绕循环)读取两个整数,然后打印它们。退出 终止“|”时的程序被输入。
- 改程序写出较小的值是:后面是较小的数字,较大的值是:后面是 更大的价值。
- 扩充程序,使其写入数字相等的行(仅当它们相等时)。
- 更改程序,使其使用双精度而不是整数。
- 更改程序,使其写出的数字在写出后几乎相等,如果两者越大越小 数字相差不到 1.0/100。
您能给我一些提示如何执行第 6 步吗?我有一些想法,但没有一个奏效..
这是新代码:
#include "C:/std_lib_facilities.h"
int main()
{
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
double a,differ=0;
char c=' ';
cout << "Enter value: \n";
while (c != '|' && cin >> a)
{
if (a > largestSoFar)
{
largestSoFar = a;
cout <<"Largest so far is: "<< largestSoFar << endl;
}
else if (a < smallestSoFar)
{
smallestSoFar = a;
cout <<"Smallest so far is: "<< smallestSoFar << endl;
}
else if(smallestSoFar >= a && a<=largestSoFar)
cout << a << endl;
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
【问题讨论】: