您能帮我解决简单的问题吗?我对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循环组成的程序(每次循环)读取两个int,然后打印它们。当终止符“ |”时退出程序 输入。
- 更改程序以写出较小的值:后跟较小的数字,较大的值是:后接较大的值。
- 增强程序,以便在数字相等的情况下(仅)将数字相等的行写入行中。
- 更改程序,使其使用双精度而不是整数。
- 更改程序,使其写出的数字几乎相等,如果两个数字相差小于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();
}
我不知道如何在不使用向量的情况下正确执行此操作。
您不需要向量。描述正确地指出,两个变量就足够了:
// Declare these variables before the loop
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
修改循环以读入a
,而不是a
和b
。根据smallestSoFar
和检查新输入的值largestSoFar
,进行打印,然后根据需要重新分配最小和最大值。请注意,您第一次应该同时看到两个打印输出-到目前为止最大的输出和迄今为止最小的打印输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句