【发布时间】:2017-11-09 00:14:29
【问题描述】:
所以,我是 C 的新手,这是我第一次上课的项目。我基本上需要一个程序来询问用户他想要多少个问题,然后检索一个可以是 oct/dec/hex(它是随机的)的最大 8 位正数,然后要求用户将其转换为随机基数。例如,如果我得到一个十进制数,它会随机要求我将其转换为十六进制或八进制。在每个问题的结尾,它会说明我的转换是对还是错,并在程序结束时显示我做对了多少问题。
一切正常,直到我开始输入随机字母/字符时,它要求我转换为十六进制以外的字符。例如,如果它要求我将八进制转换为十进制,如果我输入一个字母,它有时会说它是对的,它还会跳过问题并继续循环,直到它得到一个十六进制。
我真的不知道我能做什么。这是我的代码:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int rightanswers = 0;
int answer;
int nquestions;
printf("Number of questions:");
scanf("%d", &nquestions);
srand((unsigned int) time(NULL));
unsigned char questions[nquestions];
for (int i=1; i<=nquestions; i++)
{
questions[i] = (rand()%255)+1;
int randomnumb = (rand()%6)+1;
switch(randomnumb)
{
case 1:
printf("\nConvert 0%o to base 10:", questions[i]);
scanf("%d", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 2:
printf("\nConvert 0%o to base 16:", questions[i]);
scanf("%x", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 3:
printf("\nConvert %d to base 8:", questions[i]);
scanf("%o", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 4:
printf("\nConvert %d to base 16:", questions[i]);
scanf("%x", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 5:
printf("\nConvert 0x%x to base 8:", questions[i]);
scanf("%o", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
case 6:
printf("\nConvert 0x%x to base 10:", questions[i]);
scanf("%d", &answer);
if (answer == questions[i])
{
rightanswers++;
printf("Right!");
}
else
{
printf("Wrong!");
}
break;
}
}
printf("\nYou got %d conversions right!", rightanswers);
return 0;
}
【问题讨论】:
-
如果您从不验证
scanf的返回,那么您如何有信心从那时起处理有效数据? -
@DavidC.Rankin 如何验证 scanf 的返回?我正在尝试查找它,但我越来越困惑!
-
示例
if (scanf("%d", &answer) != 1) { /* handle error */ }或更好,int rtn; rtn = scanf("%d", &answer); if (rtn == EOF) { /* user canceled input (ctrl+d) */ } else if (rtn == 0) { /* handle matching or input failure */ } else if (rtn == 1) { /* good input -- do your thing */ }
标签: c