简体   繁体   English

c return int值不起作用

[英]c return int value doesn't work

This is my code: 这是我的代码:

#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;
}

This program calculates wheter a number is prime or not. 该程序计算数字是否为质数。
If i give number 13 as input, the function num_1 has value 1 into tmp_1 and function num_2 has value 1 into tmp_2 and both are correct. 如果我给数字13作为输入,该函数num_1具有值1tmp_1和功能num_2具有值1tmp_2又都是正确的。
The problem is that tmp=tmp_1+tmp_2 return a big big big value and i don't understand why. 问题是tmp=tmp_1+tmp_2返回了很大的价值,我不明白为什么。

You are calling the functions num_mezzo_1() and num_mezzo_2() but you are not storing their return values, so your variables tmp_1 and tmp_2 remain uninitialised. 您正在调用函数num_mezzo_1()num_mezzo_2()但没有存储它们的返回值,因此变量tmp_1tmp_2仍未初始化。

Edit: Try changing the code 编辑:尝试更改代码

    num_mezzo_1(num);
    num_mezzo_2(num);

to

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

in the else block and see if you get what you expect. 在else块中,看看您是否得到了期望的结果。

Working code: 工作代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM