数组搜索vs嵌套在c ++中的else

时间:2013-05-21 06:21:24

标签: c++ arrays search loops

这个循环的数组搜索版本是什么?所以下面这个循环没有嵌套的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++;
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
}