我需要获取两个整数并将其相加并打印相加的值。我写了一个工作程序。另一个要求是检查输入值是否不是整数,如果不是整数,则在不关闭程序的情况下,应再次请求输入。
C代码
#include <stdio.h>
void main()
{
int a,b,c;
printf("This is a Addition program");
printf("\n Enter value of a:");
scanf("%d",&a);
printf("\n Enter value of b:");
scanf("%d",&b);
c=a+b;
printf("\n The added value is %d",c);
}
最佳答案
这里有一些代码可以完全满足您的要求。昨天David C Rankin发布了answer基本相同question在堆栈溢出中。
这段代码基本上是 David 提供的:
#include <stdio.h>
static int getInt(const char *prompt)
{
int value;
char c;
while(printf("%s",prompt) && scanf("%d", &value) !=1)
{
do { c = getchar(); } while ( c != '\n' && c != EOF ); // flush input
printf ("Invalid Entry, Try Again...\n");
}
return value;
}
int sum(int a , int b) { return ( a + b ); }
int main(){
int a , b;
a = getInt("Please enter a number");
b = getInt("Please enter a number");
printf("Sum is :%d" , sum(a,b));
}
函数getInt检查输入并提示输入错误。
关于检查输入类型,无需退出程序并重新启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26322633/