提问人: 提问时间:11/25/2022 最后编辑:Dominique 更新时间:11/25/2022 访问量:32
我确保用户输入一个有效的数字。如果 people 没有输入数字,if 语句会以某种方式起作用?这是如何工作的?
I’m making sure the user enters a number a valid number. If persons doesn’t enter a number, the if statement somehow works? How is this working?
问:
这只是我们大学小组工作的一小部分。我们必须展示我们的代码并解释代码的每个部分是如何工作的。
我们希望确保用户输入整数,并在用户未输入有效数字时提示用户重新输入。
我们设法想出了一个解决方案,但我无法弄清楚它为什么有效。
在尝试提出解决方案时,我们想使用
numberchecker==input\[i\]
if(!(numberchecker==input\[i\]))
但是,它与我们想要的相反,所以我删除了“!”,现在它以某种方式起作用了?为什么/如何发生这种情况?if 语句不应该只在我们输入整数时触发吗?
#include <stdio.h>
int main()
{
int i,x,input[128],answer,numberchecker;
printf("Input number of numbers: ");
scanf("%d",&x);
for(i=0;i<x;i++)
{
printf("Input number %d:",i+1);
scanf("%d",&input[i]);
numberchecker==input[i];
if(numberchecker==input[i])
{
do
{
printf("\nInvalid number! Please try to input a valid number\n\nInput number %d:",i+1);
scanf("%d",&input[i]);
numberchecker==input[i];
}
while(numberchecker==input[i]);
}
}
}
答:
0赞
chux - Reinstate Monica
#1
但是,它与我们想要的相反,所以我删除了“!”,现在它以某种方式起作用了?
它不可靠地工作,而是依赖于未定义的行为。
为什么/如何发生这种情况?
这是未定义的行为。
if 语句不应该只在我们输入整数时触发吗?
不。这是未定义的行为。
用于读取一行用户输入,并作为如何解析它的基础。fgets()
strtol()
评论
fgets
strtol
sscanf
scanf
numberchecker==input[i];
==
=