切换声明

时间:2016-07-19 17:38:38

标签: c++ switch-statement

使用switch语句创建一个代码,当除以8时输出余数(0,1,2,3等)。用户输入20从0到99的整数。每个余数应显示其总计数。

例如:这是输出的方式。

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 ++吗?

1 个答案:

答案 0 :(得分:0)

Switch语句应该具有测试条件,然后根据结果执行命令。这里的问题是你正在测试一个没有值的变量。括号包含正在测试的数据。这些情况是根据结果值执行给定的命令。你在这里测试的是x[i] % 8。这应该放在括号中。案件应该附加价值。

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

case将测试括号中所采取操作的结果是否等于其指定值(例如0,1,2,3或默认值)并执行指定的命令。

相关问题