-3

这个循环的数组搜索版本是什么?所以下面这个相同的循环没有嵌套的 if else。

Test t;
int A;
int B;
int C;
int D;
int F;

for(int i = 0; i < gradeCount;i++){
    if(t.getScore() <= 100 && t.getScore() >= 90)
        A++;
    else if(t.getScore() >= 80 && t.getScore() <= 89)
        B++;
    else if(t.getScore() >= 70 && t.getScore() < 79)
        C++;
    else if(t.getScore() >= 60 && t.getScore() < 69)
        D++;
    else if(t.getScore() <= 59)
        F++;
}
4

2 回答 2

0

这个程序是不言自明的。希望能帮助到你。

#include <iostream>
#include <string>
using namespace std;


int main()  {

  int rank[5]={0};

  //rank[0] is grade F
  //rank[1] is grade D
  //rank[2] is grade C
  //rank[3] is grade B
  //rank[4] is grade A

  int num=0;
  cout<< "Enter a number b/w 0-100, press -1 to exit"<<endl;

  while(num != -1)
  {
     cin>>num;
     int oneTenthOfNum = num/10;
     int index = (oneTenthOfNum<=5)? 0: oneTenthOfNum%5;
     rank[index]++; 
  }

  return 0;
}
于 2013-05-21T07:05:43.310 回答
0
int results[5];
for(int i = 0; i < gradeCount; i++) {
   //if you are between 99 and 90
       //index will get set to 0
       //ex 9 - 95/10 = 0
   //if you are between 89 and 80
       //index will get set to 1
       //ex 9-89/10 = 1
   int index = 9 - t.getScore()/10;
   //if 100 or larger, we have to set it to 0, otherwise index would be negative
   if(index < 0) index = 0;
   //if less than 50, index will be too large and nothing is worse than F
   if(index >= 5) index = 4;
   results[index]++
}

最初在单个变量 A、B、C、D、F 中的计数,现在保存到一个数组“结果”中。

在哪里:

结果 [0] 是 A

结果[1]是B

...

结果[4] 为 F

于 2013-05-21T06:28:54.677 回答