C 中的 Int 变量在未调用时发生变化

发布于 2025-01-15 02:17:59 字数 1468 浏览 3 评论 0原文

提前道歉,我对此很陌生。

我正在尝试根据具有关联分值的 POINTS 数组对“拼字游戏”进行评分。

  1. 我首先获取word1字符串的长度。
  2. 然后,我创建一个 for 循环,该循环将小写字母的值减去 97(以达到索引 0)并将其添加到数组中。

您可以忽略其余代码,因为这就是问题所在。虽然 stringlength 变量仅定义一次,但我发现它在 for 循环的第二个循环期间发生了某种变化。四字母单词最初的 stringlength4,但是 for 循环将其更改为 1第二次运行。

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

// Points assigned to each letter of the alphabet
int POINTS[] = { 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void) {
    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    int stringlength = strlen(word1);

    int array[] = {};
    int array2[] = {};

    //Create an array with each letter
    for (int index = 0; index < stringlength; index++) {
        //THE BELOW LINE IS WHERE "STRINGLENGTH" CHANGES TO "1" ON THE SECOND LOOP
        array[index] = word1[index] - 97;
        array2[index] = POINTS[array[index]];
    }

    int score = 0;

    for (int index2 = 0; index2 < stringlength; index2++)
        score += array2[index2];

    printf("%i", stringlength);

    printf("\n");
}

我知道我可以创建一个辅助 stringlength 变量,但我知道这是糟糕的编程,我很想知道我做错了什么。

任何帮助将不胜感激。谢谢!

Apologies in advance, I'm very new to this.

I am attempting to score "scrabble words" according to a POINTS array with associated score values.

  1. I first get the length of the string of word1.
  2. I then create a for loop that takes the value of the lower case letter minus 97 (to get to the 0 index) and adds it to the array.

You can ignore the rest of the code, as this is where the issue lies. While the stringlength variable is only defined once, I've found that it somehow changes during the second cycle of the for loop. A four letter word will originally have a stringlength of 4, however the for loop changes it to 1 on the second run.

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

// Points assigned to each letter of the alphabet
int POINTS[] = { 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void) {
    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    int stringlength = strlen(word1);

    int array[] = {};
    int array2[] = {};

    //Create an array with each letter
    for (int index = 0; index < stringlength; index++) {
        //THE BELOW LINE IS WHERE "STRINGLENGTH" CHANGES TO "1" ON THE SECOND LOOP
        array[index] = word1[index] - 97;
        array2[index] = POINTS[array[index]];
    }

    int score = 0;

    for (int index2 = 0; index2 < stringlength; index2++)
        score += array2[index2];

    printf("%i", stringlength);

    printf("\n");
}

I know I could just create a secondary stringlength variable but I know that's bad programming and I'd love to know what I'm doing wrong.

Any help would be greatly appreciated. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光暖心i 2025-01-22 02:18:00

代码中存在多个问题:

  • int array[] = {};是语法错误。数组定义必须至少有一个初始值设定项。在您的情况下,您必须定义长度为 stringlengtharray

    int 数组[字符串长度];
    

    您的编译器似乎接受定义并创建一个空数组,该数组的长度不足以存储字母分数:您在两个 for 循环中都有未定义的行为,访问超出其边界的数组元素。未定义的行为意味着任何事情都可能发生,包括您观察到的情况。

  • word1[index] - 97 中,您对 'a' 的 ASCII 值进行硬编码。这是不好的做法,你应该这样写:

    word1[索引] - 'a'
    

    但请注意,您在此表达式中还做出了 2 个更无声的假设:

    • 您假设 word1 仅包含小写字母,应在用户可以键入任何字符串时对其进行测试。
    • 您假设小写字母形式在执行字符集中是连续的,这对于 ASCII 来说是正确的,但 C 标准不保证。由于所有现代系统都使用 ASCII 作为标准字符,因此这个假设是可以的。
  • printf("%i", stringlength); 输出字符串长度,而不是分数。

这是一个没有附加数组的修改版本:

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

// Points assigned to each letter of the alphabet
int POINTS[] = { 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void) {
    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    //Compute the score for player 1
    int score1 = 0;
    for (int index = 0; word1[index] != '\0'; index++) {
        unsigned char c = word1[index];
        if (c >= 'a' && c <= 'z') {
            // assuming ASCII character set
            score1 += POINTS[c - 'a'];
        }
    }

    //Compute the score for player 2
    int score2 = 0;
    for (int index = 0; word2[index] != '\0'; index++) {
        unsigned char c = word2[index];
        if (c >= 'a' && c <= 'z') {
            // assuming ASCII character set
            score2 += POINTS[c - 'a'];
        }
    }
    printf("Player 1: %d\n", score1);
    printf("Player 2: %d\n", score2);
    return 0;
}

如果您了解函数,您可以编写一个函数 intcompute_score(const char *word) 以避免重复代码并提高可读性。

There are multiple problems in the code:

  • int array[] = {}; is a syntax error. There must be at least one initializer for an array definition. In your case, you must define array with a length of stringlength with:

    int array[stringlength];
    

    your compiler seems to accept the definition and create an empty array, which is not long enough to store the letter scores: you have undefined behavior in both for loops, accessing array elements beyond their boundaries. Undefined behavior means anything can happen, including what you observe.

  • in word1[index] - 97, you hard code the ASCII value of 'a'. This is bad practice, you should write this instead:

    word1[index] - 'a'
    

    note however that you also make 2 more silent assumptions in this expression:

    • you assume that word1 only contains lowercase letters, which should be tested as the user can type any string.
    • you assume that the lowercase letters form are contiguous in the execution character set, which is correct for ASCII but not guaranteed by the C Standard. Since all modern systems use ASCII for the standard characters, this assumption is OK.
  • printf("%i", stringlength); outputs the string length, not the score.

Here is a modified version without additional arrays:

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

// Points assigned to each letter of the alphabet
int POINTS[] = { 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void) {
    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    //Compute the score for player 1
    int score1 = 0;
    for (int index = 0; word1[index] != '\0'; index++) {
        unsigned char c = word1[index];
        if (c >= 'a' && c <= 'z') {
            // assuming ASCII character set
            score1 += POINTS[c - 'a'];
        }
    }

    //Compute the score for player 2
    int score2 = 0;
    for (int index = 0; word2[index] != '\0'; index++) {
        unsigned char c = word2[index];
        if (c >= 'a' && c <= 'z') {
            // assuming ASCII character set
            score2 += POINTS[c - 'a'];
        }
    }
    printf("Player 1: %d\n", score1);
    printf("Player 2: %d\n", score2);
    return 0;
}

If you know about functions, you could write a function int compute_score(const char *word) to avoid duplicating the code and improve readability.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文