我正在为入门编程课程做一个实验室
我必须确保输入了一个整数。我以为这样就可以了,但是当我输入一封信时,它会无限循环地重复。
我在另一篇文章中找到了这个解决方案
int num;
char term;
if (scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
但我不确定我做错了什么。为什么它在我的代码中不起作用?
#include <stdio.h>
int main(void)
{
int oneVar;
char term;
double numOne;
double numTwo;
double sum;
double dif;
double quo;
double mult;
int checker = 1;
do
{
printf("Please choose one of the following:\n""1) Add\n""2) Subtract\n""3) Divide\n""4) Multiply\n""5) Quit\n");
if (scanf("%d%c" , &oneVar ,&term) != 2 || term != '\n')
{
printf ("This is not valid input\n\n");
checker = 1;
}
else if (oneVar == 5)
{
printf("Thank you. Goodbye.\n");
checker = 0;
}
else if (oneVar != 1 && oneVar !=2 && oneVar != 3 && oneVar != 4)
{
printf("This is not a valid input\n\n");
checker = 1;
}
else
{
printf("Please enter the first number:\n");
if (scanf("%lf%c" , &numOne ,&term) != 2 || term != '\n')
{
printf ("This is not valid input\n\n");
checker = 1;
}
printf("Please enter the second number:\n");
if (scanf("%lf%c" , &numTwo ,&term) != 2 || term != '\n')
{
printf ("This is not valid input\n\n");
checker = 1;
}
else if (oneVar == 1)
{
sum = numOne + numTwo;
printf("The sum is: %.2lf\n" ,sum);
checker = 0;
}
else if (oneVar == 2)
{
dif = numOne - numTwo;
printf("The difference is: %.2lf\n" ,dif);
checker = 0;
}
else if (oneVar == 3)
{
quo = numOne / numTwo;
printf("The quotient is: %.2lf\n" ,quo);
checker = 0;
}
else if (oneVar == 4)
{
mult = numOne * numTwo;
printf("The product is: %.2lf\n" ,mult);
checker = 0;
}
else if (oneVar == 5)
{
printf("Thank you. Goodbye.\n");
checker = 0;
}
}
} while (checker == 1);
return(0);
}
我的教授发布了这个我不确定它有什么帮助,但我认为它可能会帮助某人为了确保用户输入的数字是一个整数,你可以使用强制转换的概念。强制转换是一种告诉 C 将变量视为不同类型的变量的方法。
所以,如果我有这样的事情:
double myDouble;
myDouble = 5.43;
printf ("%d", (int) myDouble);
它将告诉 C 打印 myDouble,但将其视为整数。只会打印 5 并且您不会收到任何类型不匹配错误。您可以使用转换来检查输入数字是否为整数,方法是将输入与数字的 (int) 转换进行比较。像这样的东西应该工作:
if(inputNum == (int) inputNum)
你仍然会得到 1.0 和 2.0 作为有效数字传递,但现在还可以。