使得在C switch语句使用数组? [英] Making a switch statement in C with an array?

查看:406
本文介绍了使得在C switch语句使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个switch语句,它接受一个单词到一个数组,然后抛出通过一个开关语句中的每个字母和分配点的每个字母取决于哪个字母是并给出对这个词的最后一点价值,我似乎无法得到阵列部分权利。任何帮助将是AP preciated!

  INT的main(){
INT letter_points = 0;
字符字[7];
INT word_length = 7;
INT I;
的printf(请输入一个Word \\ n);
scanf函数(%S字);
对于(i = 0; I< word_length;我++){开关(字){
    // 1分
    案例'A':
    案例'E':
    案例'我':
    案例'L':
    案例'N':
    案例'O':
    案例'R':
    案例'S':
    案例'T':
    案例'U':
        letter_points ++;
        打破;
    // 2分
    案D:
    案例'G':
        letter_points + = 2;
        打破;
    // 3分
    案例'B':
    情况下C:
    案例'M':
    案例'P':
        letter_points + = 3;
        打破;
    // 4分
    案例'F':
    案例'H':
    案例'V':
    案例'W':
    案例'Y':
        letter_points + = 4;
        打破;
    // 5分
    案例'K':
        letter_points + = 5;
        打破;
    // 8分
    案例'J':
    情况下'X':
        letter_points + = 8;
        打破;
    // 10分
    案例'Q':
    案例'Z':
        letter_points + = 10;
        打破;
}
}
的printf(%d个\\ N,letter_points);
返回;
}


解决方案

尝试使用这种

 开关(字[I]){

在switch语句。既然这样,你是不是你的数组中测试每个元素,即使你是遍历数组的范围。说了这么多,我会去为对方的回答通过Kerrek SB建议的方法。这是更整洁,更紧凑。

I am trying to make a switch statement that takes in a word into an array and then throws each letter through a switch statement and allocates a point to each letter depending on which letter it is and giving a final point value for the word, and I can't seem to get the array part right. Any help would be appreciated!

int main(){
int letter_points = 0;
char word[7];
int word_length = 7;
int i;
printf("Enter a Word\n");
scanf("%s", word);
for(i = 0; i < word_length; i++){

switch(word){
    //1 point
    case 'A':
    case 'E':
    case 'I':
    case 'L':
    case 'N':
    case 'O':
    case 'R':
    case 'S':
    case 'T':
    case 'U':
        letter_points++;
        break;
    //2 points
    case 'D':
    case 'G':
        letter_points += 2;
        break;
    //3 points
    case 'B':
    case 'C':
    case 'M':
    case 'P':
        letter_points += 3;
        break;
    //4 points
    case 'F':
    case 'H':
    case 'V':
    case 'W':
    case 'Y':
        letter_points += 4;
        break;
    //5 points
    case 'K':
        letter_points += 5;
        break;
    //8 points
    case 'J':
    case 'X':
        letter_points += 8;
        break;
    //10 points
    case 'Q':
    case 'Z':
        letter_points += 10;
        break;
}
}
printf("%d\n", letter_points);
return;
}

解决方案

Try using this

 switch(word[i]){ 

in the switch statement. As it stands, you are not testing each element in your array even though you are iterating over the range of the array. Having said that I would go for the approach suggested by Kerrek SB in the other answer. This is much neater and more compact.

这篇关于使得在C switch语句使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆