[英]C create Array and check for Input Error
Simple question. 简单的问题。 I am trying to build a simple script that will ask you for a number.
我正在尝试构建一个简单的脚本,要求您提供电话号码。 That integer will be the amount of numbers you will enter in total.
该整数将是您总共输入的数字量。 Then your program finds the biggest number and the smallest.
然后,您的程序将找到最大数量和最小数量。 And I have build that.
我已经建立了。 Easy.
简单。
int CHECK=100;
int a[50],size,i,max,min;
printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\nEnter %d numbers: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<size;i++){
if(max<a[i])
max=a[i];
}
printf("\nLargest element: %d",max);
printf("\n");
min=a[0];
for(i=1;i<size;i++){
if(min>a[i])
min=a[i];
}
printf("Smallest element: %d",small);
printf("\n");
return 0;
}
My question is, how can I tell to check for conditions. 我的问题是,如何告诉我检查条件。 For instance, the user can input only positive numbers and smaller than 100. So if you enter -4 or 201 an Error has to be displayed telling you to try again.
例如,用户只能输入小于100的正数。因此,如果输入-4或201,则必须显示错误,告诉您重试。 Any ideas as of how we can do that in a simple way.
关于如何以一种简单的方式做到这一点的任何想法。 Or even point me to the right direction.
甚至为我指明正确的方向。
I appreciate it. 我很感激。 Thank you.
谢谢。
It really is quite easy - at least as easy as in Python. 确实很容易-至少和Python一样容易。 I'm sticking with your
scanf
to illustrate the condition, but see @j_random_hacker's comments (++). 我坚持使用
scanf
来说明这种情况,但请参阅@j_random_hacker的注释(++)。
for(i=0; i < size; i++) {
scanf("%d",&a[i]);
if ( a[i] < 0 || a[i] > 99 ) {
fprintf(stderr, "Number '%d' is out of range, try again: ", a[i]);
i--;
}
}
By the way you had a missing {
in your code, I assume it was a transposition error. 顺便说一下,您的代码中缺少
{
,我认为这是一个转置错误。 (Consistent indentation will help pickup errors like this - it is not just a good idea in Python). (一致的缩进将有助于解决此类错误-这在Python中不仅仅是一个好主意)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.