0

How to Program の練習問題 2.19 のプログラムを書こうとしていたのですが、うまくいきませんでした。

このプログラムは、ユーザーに 3 つの整数を入力させ、それらの整数のsumaverage、およびを表示させることになっています。product

私が抱えている唯一の問題は、最大と最小を表示することです。プログラムを実行して 3 つの整数を入力する(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)

残りのすべての if 条件についても同じことを行います。

編集:コンマで区切られたすべての式が評価されるため、そのようなものがある場合 x = 5, y = 6;、それらの両方を評価し、x を 5 に、y を 6 z = (x=5, y=6);に設定しますが、y = 6 のように y と同じように z を 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

コンマの代わりに && ie が必要です

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 であり、コンマの代わりにこの演算子を使用する必要があることがわかりました,andしかし、同等の記​​号の代わりにthey キーワードを使用できることをご存知でしたか?:

if ( x < y and x < z ) {

}
于 2012-09-22T20:37:14.320 に答える