该程序测试哥德巴赫猜想,将给定的偶数打印为两个素数之和。打印第一个之后,给定的整数将迭代 2 ,然后找到该整数的两个素数之和。依此类推,直到程序被用户中断。
这个问题是程序在每次执行打印语句后都会打印“0”。
代码:
#include <stdio.h>
#include <math.h>
int GC(int goldsum); //function prototype
int main()
{
int goldsum;
printf("Enter an even integer greater than 5: ");
scanf("%d", &goldsum);
printf("%d\n", GC(goldsum));
goldsum = goldsum + 2;
printf("%d\n", GC(goldsum));
}
int GC(int goldsum) //function definition
{
int i, j; //prime addends
int div1, div2; //divisors
char prime1, prime2;
for (i=2 ;i<goldsum ;i++) //when number is less than goldsum, run this loop iterating by 1
{
prime1 = 1;
for (div1=2 ;div1<i ;div1++) //this loop determines if "i" is prime.
if (i % div1 == 0) //if yes, the prime number is stored in "i"
prime1 = 0;
if (prime1)
{
for (j=3; j<goldsum; j+=2) //when number is less than goldsum, run this loop iterating by 2
{
prime1 = 1;
for (div2=2; div2<j; div2++) //this loop determines if "j" is prime.
if(j % div2 == 0) //if yes, the prime number is stored in "j"
prime1 = 0;
if (prime1)
if (i + j == goldsum) //If i + j = goldsum, it prints the result.
{
printf("%d + %d = %d\n",i ,j , goldsum);
return 0;
}
}
}
}
return 0;
}
输出:
Enter an even integer greater than 5: 10
3 + 7 = 10
0
5 + 7 = 12
0
我希望它看起来像:
Enter an even integer greater than 5: 10
3 + 7 = 10
5 + 7 = 12
最佳答案
仅使用GC(goldsum);
而不是printf("%d\n", GC(goldsum));
关于c - 如何修复 C 中 print 语句执行后程序打印 0 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335891/