如何在c中限定取值?

来源:百度知道 编辑:UC知道 时间:2024/05/21 09:19:12
一道题:
输入两个自然数,输出他们的和,输入格式 Input Format 两个自然数x和y(0<=x,y<=32767) 输出格式 Output Format 一个数,即x和y的和
我不会限定取值范围,就输入了:
#include"stdio.h"
main()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
printf("%d",c);
}
他居然验证过了,请给我讲讲,如何再c中限定取值。

#include<stdio.h>
void main()
{
long a,b,c;
scanf("%ld %ld",&a,&b);
if(a>=0&&b<=32767)
{
c=a+b;
printf("%ld",c);
}
else
printf("input num wrong") ;
}
这个程序应该正确,我刚在我的电脑上用BC31做过了。要不然你也试试?
我之所以要把你那个改为长整形,是因为你的32767已经不是整形的表示范围了。

#include"stdio.h"
main()
{
int a,b,c;
if(a<=0&&b<=32767)
{
scanf("%d%d",&a,&b);
c=a+b;
printf("%d",c);
}
else
printf("input num wrong") ;
}