2012-06-09 64 views
-1

这是我的代码:ç返回int值不起作用

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

这个程序计算wheter一个数是素与否。
如果我给第13号作为输入,功能num_1有值1tmp_1和功能num_2具有值1tmp_2并且都是正确的。
问题是tmp=tmp_1+tmp_2返回一个大大大价值,我不明白为什么。

回答

6

您所呼叫的功能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); 

,看看你得到你所期望的。

工作代码:

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

你是什么意思与_ “我不是存储他们的价值观” _ ??? – polslinux

+0

你的函数中有变量tmp_1和tmp_2,但这些变量与主函数中的变量名称不同。这些对你的num_mezzo函数是本地的。因此,main()中的tmp_1和tmp_2永远不会被初始化。 – mathematician1975

+0

我已经用类似的方式解决了:D但是非常感谢:) – polslinux