Ram*_*fan 0 c input multiple-conditions
这是一个检查共素对的程序.
我正在尝试编写一个程序来接收整数输入,直到用户输入0,这很容易在数组的帮助下解决(我已经用数组做了)因为一次只能读取一个值并检查.使用数组它只是:
for(i = 0; i < n-1; i++)
然后比较v[i]和v[i+1]
我试图在没有数组的情况下应用这种精确的检查算法,但是,读取两个值并比较它们,不知何故,只有当我多次输入0,有时两次,有时三次时,循环才会结束.
#include <stdio.h>
int gcd1(int a, int b) //function containing Euclid's algorithm
{
while (b != 0)
{
int temp = a%b;
a = b;
b = temp;
}
return a;
}
int main(int argc, char * argv[])
{
int num1, num2; /* both of these vars would otherwise have a non-zero
value if I was using Try Nr.1 written in bold below was applied */
int cate = 0, flag = 1;
while(1)
{
scanf("%d %d", &num1, &num2);
if(num1 == 0 && num2 == 0)
{
break;
}
if(gcd1(num1, num2) == 1) //check if pair is co-prime
{
cate++;
}
}
printf("%d\n", cate);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试过的事情:
1 -
while(num1 != 0 || num2 != 0) /*using this inside the while(), also tried
changing the operator to &&, without a condition and a break inside the
body*/
Run Code Online (Sandbox Code Playgroud)
2 -
尝试了while(flag != 0)改变if(num1 == 0 || num2 == 0),改变了操作员,&&但它仍然是相同的,或者对我没有意义.
我需要的程序是在任何输入0处停止,例如:
25 27 12 24 11 13 0
Run Code Online (Sandbox Code Playgroud)
程序应该停在那里并告诉我有多少对是共同素数但它只在我再输入0两次时停止.
如果需要,我将发布使用数组完成的那个.
我根据布鲁诺的答案从下面更新了程序,进行了一些测试,未通过问题提供的测试.
#include <stdio.h>
int gcd1(int a, int b) //function containing Euclid's algorithm
{
while (b != 0)
{
int temp = a%b;
a = b;
b = temp;
}
return a;
}
int main(int argc, char * argv[])
{
int num1, num2; /* both of these vars would otherwise have a non-zero
value if I was using Try Nr.1 written in bold below was applied */
int cate = 0, flag = 1;
while(1)
{
scanf("%d %d", &num1, &num2);
if(num1 == 0 && num2 == 0)
{
break;
}
if(gcd1(num1, num2) == 1) //check if pair is co-prime
{
cate++;
}
}
printf("%d\n", cate);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输入:
while(num1 != 0 || num2 != 0) /*using this inside the while(), also tried
changing the operator to &&, without a condition and a break inside the
body*/
Run Code Online (Sandbox Code Playgroud)
输出for(i = 0; i < n-1; i++)是正确的,v[i]并且v[i+1]是共同素数对.
但是输入:
25 27 12 24 11 13 0
Run Code Online (Sandbox Code Playgroud)
输出while(flag != 0)但应该是if(num1 == 0 || num2 == 0).
我需要的程序是在任何输入0停止
scanf("%d %d", &num1, &num2); 在您输入2个数字之前阻塞
如果要在第一个数字为0时停止而不必读取第二个数字,则必须执行2次扫描
scanf("%d", &num1);
if(num1 == 0)
break;
scanf("%d", &num2);
if(num2 == 0)
break;
Run Code Online (Sandbox Code Playgroud)