这是一个小型C程序,我正在尝试验证用户输入。我希望用户输入3个值。条件是所有3个输入均不应具有相同的值。因此,如何循环用户输入直到满足条件(真)。这是代码。帮帮我,我是编程新手,谢谢。 :)
#include<stdio.h>
int main()
{
int u1,u2,u3;
printf("Enter 3 Numbers : "); //Printing
scanf("%d %d %d",&u1,&u2,&u3); //Asking for Input
if(u1==u2 || u2==u3 || u3==u1) //This is the condition
{
printf("Condition is not Satisfied !");
}
}
那么我该如何循环播放。谢谢。
答案 0 :(得分:0)
通过使用递归而不是循环来完成此操作的一种非常不完善的方法(请注意注释):
#include <stdio.h>
// Recursive function to verify if all the three are unequal
void is_satisfied(int v1, int v2, int v3) {
printf("Input three different values: ");
scanf("%d %d %d", &v1, &v2, &v3);
if (v1 != v2 && v2 != v3 && v3 != v1)
return; // Exiting from the recursion
else {
// If any of the three condition stated in the IF statement
// is true, then clearly not satisfied
printf("Nope! It is not satisfied...\n");
is_satisfied(v1, v2, v3);
}
}
int main(void) {
int first = 0, second = 0, third = 0;
// Using the recursion
is_satisfied(first, second, third);
// Hooray! All done...
return 0;
}
答案 1 :(得分:0)
尝试一下,
#include<stdio.h>
int main()
{
int u1,u2,u3;
while(u1==u2 || u2==u3 || u3==u1) //This is the condition
{
printf("Enter 3 Numbers : "); //Printing
scanf("%d %d %d",&u1,&u2,&u3); //Asking for Input
if(u1==u2 || u2==u3 || u3==u1)
printf("Condition is not Satisfied !\n");
else
break;
}
return 0;
}
答案 2 :(得分:0)
我建议您使用以下代码:
#include <stdio.h>
int main( void )
{
int u1,u2,u3;
for (;;) //infinite loop, equivalent to while(true)
{
printf( "Enter 3 Numbers: " );
scanf( "%d %d %d", &u1, &u2, &u3 );
if ( u1!=u2 && u2!=u3 && u3!=u1 ) break;
printf( "Error: Condition is not satisfied!\n" );
}
}
与其他答案之一相反,该解决方案的优势在于,每个循环迭代仅检查一次条件。
但是,以上代码(以及大多数其他答案的代码)有一个严重的问题:如果用户输入字母字母而不是数字,则程序将陷入无限循环。这是因为在不检查返回值的情况下调用scanf
是不安全的。有关为什么它不安全的更多信息,请参见以下页面:A beginners' guide away from scanf()