0

我试图为 How to Program 中的练习 2.19 编写一个程序,但遇到了一些困难。

该程序应该让用户输入三个整数,然后显示这些整数的sumaverageproduct

我遇到的唯一问题是显示最大和最小。当我运行程序并输入三个整数(8, 9, and 10)时,输出为Smallest is 8 AND Smallest is 9.

我希望你能告诉我为什么。

#include <iostream>
using namespace std;

int main ()
{   int x, y, z, sum, ave, prod;

    cout << "Input three different integers ";
    cin >> x >> y >> z;

    sum = x + y + z;
    cout << "\nThe sum is " << sum;

    ave = (x + y + z) / 3;
    cout << "\nThe average is " << ave;

    prod = x * y * z;
    cout << "\nThe product is " << prod;

    if (x < y, x < z)
      {cout << "\nSmallest is " << x;}

    if (y < x, y < z)
      {cout << "\nSmallest is " << y;}

    if (z < x, z < y)
      {cout << "\nSmallest is " << z;}

    if (x > y, x > z)
      {cout << "\nLargest is " << x << endl;}

    if (y > x, y > z)
      {cout << "\nLargest is " << y << endl;}

    if (z > x, z > y)
      {cout << "\nLargest is " << z << endl;}

    return 0;
}

PS我这样做是为了学习,这不是家庭作业。

4

6 回答 6

7

你需要重写这个 if 条件

if (x < y, x < z)

成为

if (x < y && x < z)

如果你有条件,对所有剩余的都做同样的事情。

编辑:所有用逗号分隔的表达式都将被评估,所以如果你有类似的东西, x = 5, y = 6;它将评估它们并将 x 设置为 5 和 y 设置为 6 但这 z = (x=5, y=6);将导致 z 设置为 6,就像 y 一样,因为 y=6 是逗号分隔项列表中的最后一项。

于 2012-09-22T20:25:29.363 回答
3
int main() {

  std::cout << "Enter three numbers: ";

  int sum = 0;
  double avg = 0.;
  int product = 0;
  int smallest = std::numeric_limits<int>::max();
  int largest = std::numeric_limits<int>::min(); // the initializers here might not be correct, but the gist is in place...

  for (int i = 0; i < 3; ++i) {
    int val = 0;
    std::cin >> val;

    sum += val;
    avg += val;
    product *= val;

    if (val < smallest) smallest = val;
    if (val > largest) largest = val;
  }
  avg /= 3.; // This can also be done in the for loop, I just forget how.

  std::cout << "Sum: " << sum;
  // etc...  The calculations are all done.
}
于 2012-09-22T20:43:00.913 回答
1

将逗号替换为 && 用于 AND 运算符,这意味着两个条件都必须为真,或者 || 这是一个 OR 运算符,如果您希望满足任何或两个条件。

来自 C++ 文档:

The comma operator (,) is used to separate two or more expressions that are included    
where only one expression is expected. When the set of expressions has to be evaluated 
for a value, only the rightmost expression is considered.
于 2012-09-22T20:25:40.683 回答
1

用于&&代替,您的 if 条件。

于 2012-09-22T20:26:12.137 回答
1

而不是逗号,你想要 && 即

if (x < y , x < z)
  {cout << "\nSmallest is " << x;}

应该

if (x < y && x < z)
  {cout << "\nSmallest is " << x;}
于 2012-09-22T20:31:14.870 回答
0

现在您意识到这&&是 AND 并且您应该使用此运算符而不是逗号,,。但是您知道您也可以使用 they 关键字and代替其等效符号吗?:

if ( x < y and x < z ) {

}
于 2012-09-22T20:37:14.320 回答