[英]How can i declare a int type input variable eg. take a input x(0<x<1000) in c?
I try to use this code我尝试使用此代码
#include <stdio.h>
int main() {
int x,y,z;
scanf("%d%d", &x, &y);
z = x + y;
printf("%d", z);
return 0;
}
The problem is: Two man have x and y dollar.问题是:两个人有 x 和 y 美元。 Take input of
x(0 < x < 10000)
and y(0 < y < 10000)
and print the summation of their dollars.输入
x(0 < x < 10000)
和y(0 < y < 10000)
并打印它们的总和。
You cannot put restriction on user entering any value.您不能限制用户输入任何值。 But you can ask user to re-enter the values again in specified limit with little modification in your code.
但是您可以要求用户在指定的限制内再次重新输入值,而无需对代码进行少量修改。
scanf("%d%d", &x, &y);
while( x <= 0 || y <= 0 || x >= 10000 || y >= 10000) {
// Suitable message for re-entry of numbers.
scanf("%d%d", &x, &y);
}
z = x + y;
printf("%d", z);
There's no standard way to do a range check as part of an input operation in C - IOW, you can't tell scanf
to reject an integer input that's outside of a specific range.作为 C - IOW 中输入操作的一部分,没有标准方法可以进行范围检查,您不能告诉
scanf
拒绝特定范围之外的整数输入。 You will have to add a range check separately:您必须单独添加范围检查:
if ( scanf( "%d%d", &x, &y ) == 2 ) // make sure both x and y are read
{
if ( 0 < x && x < 1000 && 0 < y && y < 1000 )
{
z = x + y;
printf( "z = %d\n", z );
}
else
{
printf( "Both x and y must be between 0 and 1000\n" );
}
}
else
{
printf( "At least one bad input for x or y\n" );
}
You cannot restrict scanf
to not to get an undesired integer, but you can re-take the input from the user if the value entered is bigger than 10k or smaller than 0. That would be a simple solution.您不能将
scanf
限制为不获取不需要的整数,但是如果输入的值大于 10k 或小于 0,您可以重新获取用户的输入。这将是一个简单的解决方案。
scanf("%d%d", &x, &y);
if( x > 10000 || x <= 0) {
printf("Please re-enter a value for x: \n");
scanf("%d", &x);
}
if( y > 10000 || y <= 0) {
printf("Please re-enter a value for y: \n");
scanf("%d", &y);
}
If you want you can also make a termination scenario by using "End of File" ( EOF
).如果需要,您还可以使用“文件结尾”(
EOF
)来制作终止场景。 Putting this here for source.把这个放在这里作为来源。 How to use EOF
如何使用EOF
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.