【问题标题】:Counting Function calls in ISO C89计数 ISO C89 中的函数调用
【发布时间】:2015-10-25 11:20:48
【问题描述】:

我必须为我的作业用 C 语言编写一个函数。 给定函数 is_prime(n) 和 nth_prime(n),如果 n 是素数,则第一个返回 1(如果不是,则返回 0)和 nth_prime 返回第 n 个素数,我必须编写函数 next_prime(count) 来计算时间它被调用,然后返回“count-th”数素数。 count 必须是静态无符号整数变量。 如果 n=0(n 用 scanf 给出),计数值必须重置为 0,并且函数返回第一个素数,2。
我不能使用结构、数组或递归。 我是编码新手,我不知道该怎么做。 我使用 Visual Studio 2010,我必须将其编译为 ISO C89(ANSI C)。 这些函数必须写在一个库文件中,这是唯一要评估的东西,所以我不能在 main () 函数中使用 count++。 这是我到目前为止所做的。

unsigned int next_prime( unsigned int count ) {
    if( count == 0 ) {
        if ( n=!0 ) {                       
            return nth_prime( count );
            count++;
        } else {
            count = 0;
            return 2;
        }      
    } else {    
        if ( n=!0 ) {                       
            return nth_prime( count );
        } else {
            count = 0;
            return 2; 
        }       
    }
}   

【问题讨论】:

  • 不应该是n=!0n!=0
  • 从创建静态无符号整数变量count开始。
  • 我已经创建了它,但是我把它放在了函数体之外。这是错的吗?是的,它是n!= 0,我弄错了。我很抱歉。
  • 如果一定要写函数next_prime(count)是错误的,因为全局count会被参数count遮蔽,不能在函数next_prime内部访问。跨度>
  • 我已经完成了,但 Visual Studio 给了我一个“形式参数计数的重新定义”错误 C2082 unsigned int next_prime(unsigned int count) { static unsigned int count n=0; if(count == 0) { if (n=!0) { return nth_prime(count);计数++;}否则{计数= 0; return 2;} } else { if (n=!0) { return nth_prime(count); } else {count = 0;返回 2; } } }

标签: c function counting function-calls ansi-c


【解决方案1】:

这里有一个函数可以满足你的问题:

/* the function next_prime(count) */
unsigned int next_prime(unsigned int count) {
    /* avoid "unused parameter" warning */
    (void)count;
    /* introduce this block because defining the variable count here will read to an redeclaring error */
    {
        static unsigned int count = 0;
        int n = -1;
        /* n is given with a scanf */
        scanf("%d", &n);
        /* if n=0 */
        if (n == 0) {
            /* count value must be reset to 0 */
            count = 0;
            /* return the first prime number, 2 */
            return 2;
        } else {
            /* count the time it is called */
            count++;
            /* return the "count-th" prime number */
            return nth_prime(count);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2013-07-04
    • 2023-03-11
    • 2014-11-25
    • 2014-11-07
    相关资源
    最近更新 更多