【问题标题】:c return int value doesn't workc返回int值不起作用
【发布时间】:2012-06-09 16:57:49
【问题描述】:

这是我的代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

int num_mezzo_1(int num_orig);
int num_mezzo_2(int num_orig);

int main(int argc, char *argv[]){
    int num,contatore,tmp=0,tmp_1,tmp_2;
    num=atoi(argv[1]);
    if(num <= 3){
        printf("%d è primo\n", num);
        exit(0);
    }
    else{
        num_mezzo_1(num);
        num_mezzo_2(num);
        tmp=tmp_1+tmp_2;
            //using printf to debug
        printf("t1 %d, t2 %d\n", tmp_1,tmp_2);
        if(tmp>2){
            printf("%d NON è primo\n", num);
        }
        else{
            printf("%d è primo\n", num);
        }
    }
    exit(0);
}

int num_mezzo_1(int num_orig){
    int tmp_1=0,cont_1;
    for(cont_1=1; cont_1<=(num_orig/2); cont_1++){
        if((num_orig % cont_1) == 0){
            tmp_1++;
        }
    }
    //using printf to debug
    printf("\n%d\n", tmp_1);
    return tmp_1;
}

int num_mezzo_2(int num_orig){
    int tmp_2=0,cont_2;
    for(cont_2=((num_orig/2)+1); cont_2<=num_orig; cont_2++){
        if((num_orig % cont_2) == 0){
            tmp_2++;
        }
    }
    //using printf to debug
    printf("\n%d\n\n", tmp_2);
    return tmp_2;
}

这个程序计算一个数是否是素数。
如果我将数字 13 作为输入,则函数 num_1 的值 1tmp_1 和函数 num_2 的值 1tmp_2 并且两者都是正确的。
问题是tmp=tmp_1+tmp_2 返回一个 big big big 值,我不明白为什么。

【问题讨论】:

    标签: c function return-value


    【解决方案1】:

    您正在调用函数num_mezzo_1()num_mezzo_2(),但您没有存储它们的返回值,因此您的变量tmp_1tmp_2 保持未初始化。

    编辑:尝试更改代码

        num_mezzo_1(num);
        num_mezzo_2(num);
    

        tmp_1 = num_mezzo_1(num);
        tmp_2 = num_mezzo_2(num);
    

    在 else 块中,看看你是否得到了你所期望的。

    工作代码:

    tmp=(num_mezzo_1(num)+num_mezzo_2(num));
    

    【讨论】:

    • 您的函数中有变量 tmp_1 和 tmp_2,但它们与主函数中的同名变量不同。这些对于您的 num_mezzo 函数是本地的。因此,main() 中的 tmp_1 和 tmp_2 永远不会被初始化。
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2015-06-30
    相关资源
    最近更新 更多