这个问题已经在这里有一个答案:
我试图写不使用“战俘”函数计算X ^ Y(X的Y次方)的C程序。当我输入号码的程序工作正常,但是当用户输入一个字符,不是一个数字我在与这些代码并没有停止的问题。它贯穿于项目给予消息后多次“您输入的字符是不是你已经进入了一个number.Please尝试again.The性格是不是一个number.Please再试。值为1。”有人能帮忙吗?我要疯了试图弄清楚这一点。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
if (y!=1)
printf("The character you have entered is not a number.Please try again.");
else
for(i=1;i<=y;i++)
{
val=x;
n=n*val;
}
printf("The value is %d.\n", n);
return 0;
}
当你的程序检测到无效的输入,就显示一条消息,但除此之外,就在前面继续进行,就好像一个有效的输入已经被读取。相反,它需要做的这些事情之一:
它的消息表明,该计划将提供进入新的输入,但实际上它并没有跟进。此外,如果它是第一个提示即无效,则该输入仍在等待当程序打印第二提示符下,其中它仍然是无效的,并且程序愉快地继续进行第二次读出的输入,最终印刷n
,1的初始值,而无需计算任何东西。
你需要检查多少项目SCANF成功读取:
int numItemsRead = 0;
printf("What power is the number raised to?\n");
numItemsRead = scanf("%d", &y);
if (numItemsRead!=1)
printf("The character you have entered is not a number.Please try again.");
} else {
'''
}
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
return 0;
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
也许如果u不喜欢,即使ü进入了一个无效字符程序将结束。