c - cs50 拼字游戏:无论输入什么,总是打印相同的答案
问题描述
我需要为 cs50 课程编写一个拼字游戏。现在我有这个代码,但问题是起初它总是打印“领带!” 现在它总是打印出“玩家 2 获胜!” 无论我输入什么。我认为我的错误是在 for 循环中,你将字母分配给数字,但我真的不知道如何修复它。有人可能知道怎么做吗?
// 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 compute_score(string word1);
int compute_scores(string word2);
int main(void)
{
// Get input words from both players
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");
// Score both words
int score1 = (int) compute_score;
int score2 = (int) compute_scores;
// Print the winner
if (score1 == score2)
{
printf("Tie! \n");
}
if (score1 < score2)
{
printf("Player 2 wins! \n");
}
if (score1 > score2)
{
printf("Player 1 wins! \n");
}
}
int compute_score(string word1)
{
// Compute and return score for string
int compute_score = 0;
int numb;
for (int i = 0, n = strlen(word1); i < n; i++)
{
if(isupper(word1[i]))
{
numb = word1[i] - 65;
numb = POINTS[numb];
}
if(islower(word1[i]))
{
numb = word1[i] - 97;
numb = POINTS[numb];
}
else
{
numb = 0;
}
}
compute_score = numb;
return compute_score;
}
int compute_scores(string word2)
{
// Compute and return score for string
int compute_scores = 0;
int numb;
for (int i = 0, n = strlen(word2); i < n; i++)
{
if(isupper(word2[i]))
{
numb = word2[i] - 65;
numb = POINTS[numb];
}
if(islower(word2[i]))
{
numb = word2[i] - 97;
numb = POINTS[numb];
}
else
{
numb = 0;
}
}
compute_scores = numb;
return compute_scores;
}
解决方案
当您是初学者时,几乎不存在需要使用演员表的情况。或者在极少数情况下您需要一个,您需要知道自己在做什么。
int score1 = (int) compute_score;
将函数本身的无符号地址转换为可能不适合的有符号整数。那是胡说八道。您需要调用该函数并将结果存储在int
. 任何地方都没有铸造。
我建议您阅读您最喜欢的 C 书籍中的函数。我还建议放弃 CS-50,因为这是一门糟糕的课程,教的是糟糕的做法。它在 C 程序员中的名声很差。
推荐阅读
- amazon-web-services - ECS任务定义中如何使用Entrypoint?
- python - 通过装饰器在python中缓存属性的结果
- symfony - Twig for loop 在 MySQL 数据库中找不到记录
- sql - SQL 列出所有拥有实际所有者的公寓
- react-native - 我应该怎么做才能为 React Native CLI 应用程序创建一个 Android 构建?
- kubernetes - JSR 352 WebSphere Liberty 批处理的 Kubernetes 滚动更新
- azure - 当我们说我们的 ASP.NET 核心 Web API 是一个微服务时?
- php - 为传单创建大型 PHP 数组时的内存问题
- amazon-web-services - Route 53 记录集无法解析 Elastic Beanstalk 实例
- api - Firebase 云消息传递主题统计 API