#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.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 };
char ALPHABET[] = { 'a' , 'b', 'c', 'd', 'e', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
int main(void) {
string word1 = "dog";
int score;
int tile;
int points;
int index;
int finish = strlen(word1);
for (tile = 0, index = 0, score = 0; tile == finish; index++) {
if (word1[tile] == ALPHABET[index]) {
points = index;
score = score + POINTS[points];
tile++;
index = -1;
}
}
printf("%i\n", score);
}
该程序返回的值0
不是我认为应该5
基于字母分数的值?请给我一些有关如何完成此操作的见解。我不应该在循环内部使用Iffor
循环吗?感谢您的阅读(如果有人这样做)。
请记住,您正在使用基于零的索引。
您的for
循环正在使用此:
tile == finish
它应该是:
tile < finish
“ dog”的长度为3,因此索引位置为0到2。
这至少是您的代码问题的一部分。
就像其他人所说的那样,您的循环需要一个嵌套循环,该循环可以迭代所有字母。找到匹配项后,您可以break
跳出该内循环。
另外,您还有:
'd', 2
'g', 4
'o', 3
总计为9。这是基于您的代码包含两个e
字符的情况。
另一个问题是您重置index
为,-1
因此从头开始重新启动。
综上所述:
for
循环。break
找到匹配项后,便会退出内部循环。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句