2013-05-21 30 views
-3

什么是该循环的数组搜索版本?所以下面这个相同的循环没有嵌套if else。数组搜索vs嵌套如果其他人在c + +

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++; 
} 
+0

你想知道什么?..? –

+0

plz换句/改写你的问题/ –

+1

@AhmedZ。改写为 – user12074577

回答

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]是一个

结果[1]乙

...

结果[4]是F

+0

您能解释一下这段代码吗?我也清理了OP。 – user12074577

+0

清理它,并添加评论...不是一个完美的解决方案,但我不知道什么问题是开始。 – user871289

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; 
}