C中的int变量在未被调用时更改 [英] Int Variable in C Changing When Not Called
本文介绍了C中的int变量在未被调用时更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提前道歉,我对此还很陌生。
我正在尝试根据POINTS
数组和关联的分数值对拼写单词进行评分。
- 我先获取
word1
的字符串长度。 - 然后我创建了一个
for
循环,该循环将小写字母减去97(以得到0索引)的值添加到数组中。
您可以忽略其余代码,因为这就是问题所在。虽然stringlength
变量只定义了一次,但我发现它在for
循环的第二个周期中以某种方式发生了变化。四个字母的单词最初的stringlength
为4
,但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("
");
}
我知道我只能创建第二个stringlength
变量,但我知道这是糟糕的编程,我很想知道我做错了什么。
任何帮助都将不胜感激。谢谢!
推荐答案
代码中存在多个问题:
int array[] = {};
是语法错误。数组定义必须至少有一个初始值设定项。在您的情况下,您必须定义长度为stringlength
的array
:
您的编译器似乎接受了定义并创建了一个空数组,该数组的长度不足以存储字母分数:您在两个int array[stringlength];
for
循环中都有未定义的行为,访问超出其边界的数组元素。未定义的行为意味着任何事情都可能发生,包括您观察到的内容。在
word1[index] - 97
中,您硬编码'a'
的ASCII值。这是不好的做法,您应该改为这样写:word1[index] - 'a'
但是请注意,您还在此表达式中做了两个更隐蔽的假设:
- 您假定
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] != ' '; 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] != ' '; index++) {
unsigned char c = word2[index];
if (c >= 'a' && c <= 'z') {
// assuming ASCII character set
score2 += POINTS[c - 'a'];
}
}
printf("Player 1: %d
", score1);
printf("Player 2: %d
", score2);
return 0;
}
如果您了解函数,可以编写函数int compute_score(const char *word)
以避免重复代码并提高可读性。
这篇关于C中的int变量在未被调用时更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文