这是一个简单的介绍课程问题,它要求编写一个程序,要求用户输入3个数字,并确定最大和最小的数字.仅使用if语句.我认为它写了这样的东西,但是有可能只使用3次或更少的比较吗?我想什么时候y > largest
,它也告诉我们其他的东西呢?
这是我到目前为止所尝试的:需要进行4次比较.
int x, y, z;
int smallest, largest;
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;
smallest = x;
largest = x;
if (y > largest)
largest = y;
if (z > largest)
largest = z;
if (y < smallest)
smallest = y;
if (z < smallest)
smallest = z;
cout << "largest: " << largest << ", and smallest: " << smallest << endl;
Run Code Online (Sandbox Code Playgroud)
Luc*_*ore 10
您的代码的问题在于您丢失了大量信息.在诸如此类的"挑战"中,你必须充分利用你拥有的东西.所以,当你说,例如
if (y > largest)
Run Code Online (Sandbox Code Playgroud)
不要只是对待true
案件.当条件不成立时,也要尝试推理案例.
if ( x < y )
{
smallest = x;
biggest = y;
}
else
{
smallest = y;
biggest = x;
}
if ( z < smallest )
smallest = z;
else if ( z > biggest )
biggest = z;
Run Code Online (Sandbox Code Playgroud)
这只包含3个比较.
归档时间: |
|
查看次数: |
40233 次 |
最近记录: |