有没有办法在 switch 语句 case (C) 中使用数组?

问题描述 投票:0回答:1

我正在做一个cs50问题集,我必须做一个拼字游戏,基本上是两个人写一个单词,单词中的每个字母都会给出一定的分数,即。 A 给 1 分,Z 给 10 分 我试图使用 switch 语句和几个包含每个字母及其给出的点数的字符数组来制作存储系统。数组“One”存储给出一个点的字母,“Two”存储给出两个点的字母,依此类推 但我发现我不能将数组放在 x 位置(案例 x:) 所以我尝试了一些事情并得到了这个 有没有办法提高效率,或者我应该返回 switch 语句还是什么?

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    //get the strings from the players and store them in a string data type
    string p1 = get_string("Player 1: ");
    string p2 = get_string("Player 2: ");
    //make score data types for each player
    int score1 = 0;
    int score2 = 0;
    char one[20] =        {'a','A','e','E','i','I','l','L','n','N','o','O','r','R','s','S','t','T','u','U'};
    char two[4] = {'d','D','g','G'};
    char three[8] = {'b','B','c','C','m','M','p','P'};
    char four[10] = {'f','F','h','H','v','V','w','W','y','Y'};
    char five[2] = {'k','K'};
    char eight[4] = {'j','J','x','X'};
    char ten[4] = {'q','Q','z','Z'};
    int str = strlen(p1);
    for(int N = 0; N < str; N++)
    {
        if(p1[N] == one[0] || p1[N] == one[1] || p1[N] == one[2] || p1[N] == one[3] || p1[N] ==   one[4] || p1[N] == one[5] || p1[N] == one[6] || p1[N] == one[7] || p1[N] == one[8] || p1[N] == one[9] || p1[N] == one[10] || p1[N] == one[11] || p1[N] == one[12] || p1[N] == one[13] || p1[N] == one[14] || p1[N] == one[15] || p1[N] == one[16] || p1[N] == one[17] || p1[N] == one[18] || p1[N] == one[19])
        {
            score1++;
        }else if(p1[N] == two[0] || p1[N] == two[1] || p1[N] == two[2] ||p1[N] == two[3])
        {
            score1 += 2;
           }else if(p1[N] == three[0] || p1[N] == three[1] || p1[N] == three[2] || p1[N] == three[3] || p1[N] == three[4] || p1[N] == three[5] || p1[N] == three[6] || p1[N] == three[7])
            { 
            score1 += 3;
        }
    }
}
arrays c switch-statement cs50
1个回答
0
投票

我的 C 无法再胜任此任务,但您可以这样做:

  • 创建一个 26 元素数组,每个元素包含分数 对应的字母 A - Z。
  • 迭代单词。
  • 将每个字母转换为大写并获取该字母的 ASCII 值。
  • 减去 65(ASCII A 为 65)。如果您此处的值为负数或在 超过 25(Z) 字符无效。
  • 使用该值作为字母分数数组的偏移量,并将该值添加到单词分数中。
© www.soinside.com 2019 - 2024. All rights reserved.