gpt4 book ai didi

c - 如何保持比较整数对,直到用户输入没有数组的 0?

转载 作者:太空宇宙 更新时间:2023-11-04 05:22:43 24 4
gpt4 key购买 nike

这是一个检查互质对的程序。

我正在尝试编写一个程序来接收整数输入,直到用户输入 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;
}

我尝试过的事情:

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*/

2 -

尝试了 while(flag != 0)这改变了 if(num1 == 0 || num2 == 0) , 将运算符更改为 &&也是,但它仍然是一样的,或者对我来说没有意义。

我需要的程序是在任何输入 0 处停止,例如:

25 27 12 24 11 13 0 

程序应该停在那里并告诉我有多少对是互质数,但它只会在我再输入 0 两次时停止。

最佳答案

What I need from the program is to stop at any input 0

scanf("%d %d", &num1, &num2); 在您输入 2 个数字之前一直阻塞

如果您想在第一个数字为 0 时停止而不必读取第二个数字,则必须执行 2 scanf

scanf("%d", &num1);

if(num1 == 0)
break;

scanf("%d", &num2);

if(num2 == 0)
break;

关于c - 如何保持比较整数对,直到用户输入没有数组的 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54075985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com