c - 如何修复 C 中 print 语句执行后程序打印 0 的问题?

标签 c function

该程序测试哥德巴赫猜想,将给定的偶数打印为两个素数之和。打印第一个之后,给定的整数将迭代 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/

相关文章:

function - Common Lisp 函数没有返回值

c - 调用 clock() 时出现段错误

c - 字符串变量的安全处理

javascript - 如何编写 JS 函数来执行某些操作,然后在该过程完成后返回?

Python,在我的 Python 代码中得到了一个意外的关键字参数

c++ - 将数组传递给函数

缓存来自浏览器的传出数据

c - 修改内存映射文件时通知/发出信号

c - 递归或错误检查互斥体?

c++ - 使用来自自身 C++ 的变量