【问题标题】:Converting into a function转换为函数
【发布时间】:2015-02-12 00:55:59
【问题描述】:

这个程序对我来说很好用,但我一直在尝试找到一种方法来包含一个函数,该函数可以找到我正在寻找的素数。我只是不明白如何将函数放入我的程序中。该程序会在给定区间内找到孪生素数,以防万一。

#include <stdio.h>
#include <math.h>

void main()
{
    int low, high, n, count, i;
    scanf ("%d %d", &low, &high);
            count=0;
            n=0;
    if (low<=3)
        count=count+1;
    while (n<low)
        n=n+6;
    while (n<high) {
        i=1;
        int check;
                    check=0;
        while (i*i<n+1) {
            i=i+1;
            if ((n-1)%i==0 || (n+1)%i==0)
                check=1;
        }
        if (check!=1)
            count=count+1;
        n=n+6;
    }
    printf("There are %d twin primes between %d and %d\n", count, low, high);
        printf(" \n");
}

【问题讨论】:

  • 总是int main...
  • ...它是一个函数..

标签: c function while-loop primes


【解决方案1】:

这是你想要的吗?

int findprime(int low, int high) {
    int n, count, i;

    count = 0;
    n     = 0;
    if (low <= 3)
        count = count + 1;
    while (n < low)
        n = n + 6;
    while (n < high) {
        int check;

        i     = 1;
        check = 0;
        while (i * i < n + 1) {
            i = i + 1;
            if ((n - 1) %i == 0 || (n + 1) % i == 0)
                check = 1;
        }
        if (check != 1)
            count = count + 1;
        n = n + 6;
    }
    return count;
}

int main() {
    int low, high, count;
    count = 0;
    if (scanf("%d %d", &low, &high) == 2) {
        count = findprime(low, high);
        printf("There are %d twin primes between %d and %d\n\n", count, low, high);
    } else {
        printf("Invalid input recieved.\n\n");
        return -1;
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2013-03-26
    相关资源
    最近更新 更多