2016-07-19 29 views
-1

switch文を使用すると、8で除算したときの剰余(0,1,2,3およびその他)を出力するコードを作成します。ユーザ入力20から0までの整数20各剰余は合計カウントを表示する必要があります。switch文

例:これは出力の仕方です。

Total number with remainder 0 is 4. 
Total number with remainder 1 is 6. 
Total number with remainder 2 is 5. 
Total number with remainder 3 is 3. 
Total number of other remainder is 2. 

/

#include <iostream> 
using namespace std; 
int main() 
{ 
int i, x[20]; 
cout << "Enter 20 integer numbers from 0 to 99: " <<endl; 
for (i=1;i<=20;i++) 
{ 
    cout << "Input " << i <<":"; 
    cin >> x[i]; // above this code, its working. 
} 
int remainder ; // From here im not sure how i should do it 
switch (remainder) 
{ 
case x[i] % 8 == 0 : 
cout << "Total number with remainder zero is " << endl ; 
break; 

case x[i] % 8 == 1 : 
cout << "Total number with remainder one is " << endl ;  
break; 

case x[i] % 8 == 2 : 
cout << "Total number with remainder two is " << endl ;  
break; 

case x[i] % 8 == 3 : 
cout << "Total number with remainder three is " << endl ; 
break; 

default :  
cout << "Total of others is " << endl ; 
} 
return 0 ; 
} 

私は、switch文の一般的な考えを持っています。私はC + +とこのウェブサイトに新しいです。エラーの間は、ケースの部分です。それは私がx [i]を使うことができないと言います。だから私はちょうどxまたは他の整数を使用する必要がありますか?それぞれのケースの合計数を数える方法がわからない私はcount ++を使うべきですか?

+0

'switch(variable){case somevalue;ケースの他の値。 'case'は式ではなく値でなければなりません。彼らは 'if'ステートメントではありません。 –

+1

私の場合はケース0、ケース1などとなるでしょう... –

+1

'switch(x [i]%8){case 0:... case 1:... ... case 7:...} '。また、switch文の周りに 'for'ループが必要です。 – GreatAndPowerfulOz

答えて

0

スイッチステートメントには、テストし、その結果に基づいてコマンドを実行する条件が想定されています。ここでの問題は、値を持たない変数をテストすることです。かっこにはテスト対象のデータが含まれています。ケースは、結果の値に基づいて与えられたコマンドを実行することです。ここでテストしているのはx[i] % 8です。これはカッコで囲まれていなければなりません。ケースには値が付いているだけです。

switch (x[i] % 8) { 
    case 0: //... 
    case 1: //... 
    case 2: //... 
    case 3: //... 
    default: //... 
} 

case括弧で実行された操作の結果は、その割り当てられた値(例えば、0、1、2、3、またはデフォルト)を等しく割り当てられたコマンドを実行するかどうかをテストします。