【发布时间】:2018-08-01 21:39:20
【问题描述】:
我刚开始学习如何用 C 编程,我无法摆脱错误。这是我的程序:
/* This program rolls two dice and presents the total. It then asks the user
to guess if the next total will be higher, lower, or equal. It then rolls
two more dice and tells the user how they did. */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int dice1, dice2, total, total1= 0;
char ans[25], dans[25];
char higher[] = "HIGHER", lower[] = "LOWER", equal[] = "EQUAL";
//the following 3 lines, throws the dice and adds them.
dice1 = (rand() % 5) + 1;
dice2 = (rand() % 5) + 1;
total = dice1 + dice2;
//the next few ask the question.
printf("Will the next number be higher, lower or equal to %d ?\n", total);
puts("Type higher, lower or equal.");
// scanf("&s", ans); //had to remove this line, because apparently we can't use &s to get the string input
fgets(ans, 25, stdin);
strcpy(dans, strupr(ans));
//the next few throw the dice two more times
dice1 = (rand() % 5) + 1;
dice2 = (rand() % 5) + 1;
total1 = dice1 + dice2;
/*All of these check if the user input matches the actual output and
then tells the user if he/she was right.*/
printf("The upper string is %s.\n", ans);
if ((ans == higher) && (total1 > total))
{
printf("You're right, it is higher!\n");
}
else if ((ans == lower) && (total1 < total))
{
printf("You're right, it is lower!\n");
}
else if ((ans == equal) && (total1 = total))
{
printf("You're right. they are equal!\n");
}
else
{
printf("Your prediction was wrong.\n");
}
}
我得到的错误:
test.c:25:22: 错误:函数“strupr”的隐式声明在 C99 中无效 [-Werror,-Wimplicit-function-declaration]
strcpy(dans, strupr(ans)); ^test.c:25:22: 错误:不兼容的整数到指针转换将“int”传递给“const char *”类型的参数 [-Werror,-Wint-conversion]
strcpy(dans, strupr(ans)); ^~~~~~~~~~~/usr/include/string.h:129:70:注意:在此处将参数传递给参数“__src” extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^test.c:33:18: 错误:数组比较总是评估为假 [-Werror,-Wtautological-compare]
if ((ans == higher) && (total1 > total)) ^test.c:37:23: 错误:数组比较总是评估为假 [-Werror,-Wtautological-compare]
else if ((ans == lower) && (total1 < total)) ^test.c:41:23: 错误:数组比较总是评估为假 [-Werror,-Wtautological-compare]
else if ((ans == equal) && (total1 = total))
请帮助我解决错误。
还有,
strupr 应该在
stdlib中,为什么我仍然收到错误消息?当我将字符串转换为大写字符串时,它如何变为 int?
为什么我不能在
scanf中使用%s? (我以前用过这个)
谢谢。
【问题讨论】:
-
strupr()不是标准的 C 函数,尽管我相信它可以在 MS C 中找到。因为它没有被声明,C 编译器假定它返回一个int,它是'不适合strcpy()的参数。其余的问题似乎是因为您没有使用strcmp()来比较字符串。您还需要处理fgets()在输入数据中保留的换行符。 -
检查字符串是否相等,使用
strcmp -
ans == higher不是比较字符串的正确方法。ans和higher是指向两个不同数组的指针。这些指针永远不会相等。你应该使用strcmp(ans, higher)。而且 C 中没有标准函数可以将字符串转换为大写。 -
这看起来很糟糕:(total1 = total)) 。不是警告的原因,但可能不是你想要的。 PS:去掉所有多余的()。 if (a > b || c b) || (c