简体   繁体   English

验证输入和重复语句

[英]Verifying inputs and repeating statements

I need to take two numbers from two separate scans and find the GCD of both of them.我需要从两次单独的扫描中取出两个数字并找到它们的 GCD。 I have this currently which will take the two numbers, but I need to validate input with a function.我目前有这个将采用两个数字,但我需要使用函数验证输入。 It should work as follows, I enter a number and it checks to verify that it is a positive integer.它应该如下工作,我输入一个数字并检查它是否是一个正整数。 If not it should prompt me to say that the input is unrecognized and ask for it again.如果不是,它应该提示我说输入无法识别并再次询问。 Once I input a valid number, it should continue to ask me to put in a second one and do the same verification process.一旦我输入了一个有效的数字,它应该继续要求我输入第二个并执行相同的验证过程。 Any help with input validation and repeating the question in a function would be helpful.任何有关输入验证和在函数中重复问题的帮助都会有所帮助。


int main()
{
    int num1, num2, i, GCD;
   
    printf("Please enter a positive integer: \n");
    scanf("%d" ,&num1);
    printf("Please enter a positive integer:\n");
    scanf("%d", &num2);
if (num1 >0 && num2 > 0) {
    for(i = 1; i <= num1 && i <= num2; i++)
    {
        if(num1 % i == 0 && num2 % i == 0)
            GCD = i;
    }
}
else {
   printf("I'm sorry that number is unrecognized or negative.\n");

}
printf("The largest integer that divides both %d and %d is: %d\n",num1,num2, GCD);

    return 0;
}

you can use a do-while loop and put your scanf in there as long as you dont get a valid answer.只要您没有得到有效答案,您就可以使用 do-while 循环并将您的 scanf 放在那里。 For example:例如:

do {

   // put your scans here 

} while(num1<0 || num2<0);

Also you can catch the case if he inputs a character instead of integer input!如果他输入字符而不是整数输入,您也可以捕获这种情况! So that is a good way to repeat a prompt until you get the valid answer.所以这是重复提示直到得到有效答案的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM