0

这里是 C 的新手。我似乎在一个我必须做的问题上发生了冲突。这里的目标是制作一个用单词写出两位数的程序。或者,用户可以输入“Q”退出。这是我遇到的麻烦。谁能指出我做错了什么?

#include <stdio.h>
int main(void)
{
int digit_one;
int digit_two;
enum state {fail, quit};
int status = fail;

printf("Enter a two-digit number or press Q to quit: ");
scanf("%1d%1d",&digit_one,&digit_two);

if(digit_one == 'Q'){
status = quit;
}
else {
if (digit_one == 1) {
    switch(digit_two % 10) {
        case 0: printf("You entered: Ten"); break;
        case 1: printf("You entered: Eleven"); break;
        case 2: printf("You entered: Twelve"); break;
        case 3: printf("You entered: Thirteen"); break;
        case 4: printf("You entered: Fourteen"); break;
        case 5: printf("You entered: Fifteen"); break;
        case 6: printf("You entered: Sixteen"); break;
        case 7: printf("You entered: Seventeen"); break;
        case 8: printf("You entered: Eighteen"); break;
        case 9: printf("You entered: Ninteen"); break;
    }
    return 0;
}

switch(digit_one % 10) {

    case 2: printf("You entered: Twenty-"); break;
    case 3: printf("You entered: Thirty-"); break;
    case 4: printf("You entered: Forty-"); break;
    case 5: printf("You entered: Fifty-"); break;
    case 6: printf("You entered: Sixty-"); break;
    case 7: printf("You entered: Seventy-"); break;
    case 8: printf("You entered: Eighty-"); break;
    case 9: printf("You entered: Ninety-"); break;
}
switch(digit_two % 10) {
    case 0: break;
    case 1: printf("One"); break;
    case 2: printf("Two"); break;
    case 3: printf("Three"); break;
    case 4: printf("Four"); break;
    case 5: printf("Five"); break;
    case 6: printf("Six"); break;
    case 7: printf("Seven"); break;
    case 8: printf("Eight"); break;
    case 9: printf("Nine"); break;
}
return 0;
}
}
4

2 回答 2

3

您无法读取Q整数变量。将输入读入一个字符。

于 2013-09-24T08:23:43.640 回答
0

问题是您scanf读取一个字符串立即将其转换为整数(就是%d这样)。

您需要首先将一个字符串(带有%s或类似的)读取到缓冲区,然后检查它是否不是'Q'. 之后,您可以使用 转换为整数sscanf

http://en.cppreference.com/w/c/io/fscanf

编辑:此外,您的代码完全忽略了退出状态。

于 2013-09-24T08:46:47.117 回答