【发布时间】:2012-01-30 21:38:34
【问题描述】:
好的,我是 C 的菜鸟,但我认为代码基本且简单。该程序用于大学作业,并且应该包含“isdigit()”函数。这是代码
//by Nyxm
#include <stdio.h>
#include <ctype.h>
main()
{
char userChar;
int userNum, randNum;
srand(clock());
printf("\nThis program will generate a random number between 0 and 9 for a user to guess.\n");
/*I changed it from '1 to 10' to '0 to 9' to be able to use the isdigit() function which
will only let me use a 1 digit character for an argument*/
printf("Please enter a digit from 0 to 9 as your guess: ");
scanf("%c", userChar);
if (isdigit(userChar))
{
userNum = userChar - '0';
randNum = (rand() % 10);
if (userNum == randNum)
{
printf("Good guess! It was the random number.\n");
}
else
{
printf("Sorry, the random number was %d.\n", randNum);
}
}
else
{
printf("Sorry, you did not enter a digit between 0 and 9. Please try to run the program again.\$
}
}
当我尝试编译时,我收到以下错误
week3work1.c: In function ‘main’:
week3work1.c:14:2: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]
到底发生了什么?我迫切需要帮助。任何帮助。我真的要放弃这个程序了。为什么当我的教科书显示“%c”用于常规 ole 'char' 时,它会说它需要 'char *' 的参数?我正在使用 nano、gcc 和 Ubuntu,如果这有什么不同的话。
【问题讨论】:
-
gcc会为您的程序生成多个警告。你应该修复它们中的all。例如,您缺少#include <stdlib.h>(srand()和rand()必需)和#include <time.h>(clock()必需)。 -
@KeithThompson 编译时,我不再有错误,程序现在可以按照我的意愿运行。所以,我想我在问它是否会继续工作?因为在我的教科书中,唯一需要的预处理器语句是“#include
”,而“#include ”用于 isdigit() 函数。 -
如果你要调用这些函数,你需要我上面描述的标题。在某些情况下您可以不使用它们而逃脱,但我不会详细说明;只需添加
#include指令。如果您使用-std=c99 -pedantic,gcc 将警告函数调用。你用的是什么教材?如果它显示了一个调用rand()而没有#include <stdlib.h>的例子,或者一个调用clock()而没有#include <time.h>的例子,那么你的教科书是错误的。 -
@KeithThompson 给我的书是 Michael A. Vine 的“C Programming for the absolute 初学者第 2 版”。我注意到每章末尾的一些练习与甚至尚未接近讨论的高级主题有关。例如,在第 2 章(关于主要数据类型)的末尾,一个练习是创建一个程序,该程序使用 scanf() 来允许用户输入他们的姓名。这将是一个字符串,这一章几乎没有涵盖字符,更不用说字符串了。
-
我之前应该提到的一点:
printf和scanf格式不一样。对于printf,%c需要int类型的参数,它应该是一个字符值。对于scanf,%c需要指向char的指针。确保您正在阅读您正在使用的函数的文档。