我正在初级CS课程中,我正在尝试用C编写一个程序,要求输入一个两位数的数字并返回该数字的写出形式。我已经编写了所有代码,当我尝试数字10-19而不是其他任何代码时,它都有效。如果重要,使用C89标准编译
#include <stdio.h>
int main(void)
{
printf("\n Number to Word Conversion Program");
printf("\n\n This program takes a two-digit number and outputs the English word for the number");
int number = 0;
int numberH1 = 0;
int numberH2 = 0;
printf("\n\n Please enter a two-digit number: ");
scanf("%d", &number);
numberH1 = number / 10;
numberH2 = number % 10;
if (number == 10 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)
{
switch (number)
{
case 10:
{
printf("\n\n The number entered was Ten.\n\n");
}
break;
case 11:
{
printf("\n\n The number entered was Eleven.\n\n");
}
break;
case 12:
{
printf("\n\n The number entered was Twelve.\n\n");
}
break;
case 13:
{
printf("\n\n The number entered was Thirteen.\n\n");
}
break;
case 14:
{
printf("\n\n The number entered was Fourteen.\n\n");
}
break;
case 15:
{
printf("\n\n The number entered was Fifteen.\n\n");
}
break;
case 16:
{
printf("\n\n The number entered was Sixteen.\n\n");
}
break;
case 17:
{
printf("\n\n The number entered was Seventeen.\n\n");
}
break;
case 18:
{
printf("\n\n The number entered was Eighteen.\n\n");
}
break;
case 19:
{
printf("\n\n The number entered was Nineteen.\n\n");
}
break;
}
}
else
{
switch (numberH1)
{
case 2:
{
printf("\n\n The numer entered was Twenty");
}
break;
case 3:
{
printf("\n\n The numer entered was Thirty");
}
break;
case 4:
{
printf("\n\n The numer entered was Forty");
}
break;
case 5:
{
printf("\n\n The numer entered was Fifty");
}
break;
case 6:
{
printf("\n\n The numer entered was Sixty");
}
break;
case 7:
{
printf("\n\n The numer entered was Seventy");
}
break;
case 8:
{
printf("\n\n The numer entered was Eighty");
}
break;
case 9:
{
printf("\n\n The numer entered was Ninety");
}
break;
}
switch (numberH2)
{
case 0:
{
printf(".\n\n");
}
break;
case 1:
{
printf("-one.\n\n");
}
break;
case 2:
{
printf("-two.\n\n");
}
break;
case 3:
{
printf("-three.\n\n");
}
break;
case 4:
{
printf("-four.\n\n");
}
break;
case 5:
{
printf("-five.\n\n");
}
break;
case 6:
{
printf("-six.\n\n");
}
break;
case 7:
{
printf("-seven.\n\n");
}
break;
case 8:
{
printf("-eight.\n\n");
}
break;
case 9:
{
printf("-nine.\n\n");
}
break;
}
}
return 0;
}
答案 0 :(得分:2)
在您的代码中,
if (number == 10 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)
是一种错误的做法。你不能像这样链接逻辑运算符。
截至目前,由于operator precedence,您的代码基本上是
if ( (number == 10) || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)
评估为
if ( 1 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)
或
if ( 0 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)
这两个都将产生一个真值。
你必须像
一样使用它if ((number == 10) || (number == 11)||(number == 12).....
正如我所看到的,您已经在使用switch
语句,因此可以完全删除if
项检查。您需要添加default
案例来处理其他号码。您可以添加嵌套的switch
来完成工作。
答案 1 :(得分:0)
第一个答案是正确的,但如果您尝试使用以下条件,解决方案会更容易:
if( (number > 9) || (number < 20))
{ ...
}
请注意,在这种情况下,您只需使用:
if(number < 20)
因为您已经要求“两位数”