2017-04-16 38 views
0

我目前正在編寫一個分配程序,它需要使用函數來使用戶能夠輸入3個可變元素。我很難將這些變量返回到我的主函數中,我曾經看到過其他類似的問題,並且試圖使用指針,但無法使其工作。我嘗試低於:如何使用指針從函數返回多個值C

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

//Function Header for positive values function 
double get_positive_value(double* topSpeed, double* year, double* 
horsepower); 

int main(void){ 

    int reRunProgram = 0; 

    while (reRunProgram==0) 
    { 
     //variable declarations 
     double tS; 
     double yR; 
     double hP; 
     int menuOption; 
     int menuOption2; 

     //menu 
     printf("1.Create Bugatti\n"); 
     printf("2.Display Bugatti\n");  
     printf("3.Exit\n"); 

     //user choice 
     scanf("%d", &menuOption); 

     //Create car  
     if (menuOption == 1) { 

      //run the get positive values function 
      get_positive_value (&tS, &yR, &hP); 

      printf("top speed is %lf\n", tS); 
     } 

     //Display car (but no car created) 
     else if (menuOption == 2){ 
      printf("error no car created\n"); 
     } 

     //Exit 
     else if (menuOption ==3){ 
      exit(EXIT_FAILURE); 
     } 

    } 
    return 0; 
} 


double get_positive_value(double* topSpeed, double* year, double* 
horsepower) 
{ 
    do { 
     printf("Please enter the top speed of the bugatti in km/h\n"); 
     scanf("%lf", &topSpeed); 
    } while(*topSpeed<=0); 

    do{ 
     printf("Please enter the year of the bugatti, in four digit form (e.g. 1999)\n"); 
     scanf("%lf", &year); 
    } while(*year<=0); 

    do{ 
     printf("Please enter the horsepower of the bugatti\n"); 
     scanf("%lf", &horsepower); 
    } while(*horsepower<=0); 
} 
+1

C或C++?你把這個問題標記爲C++,但是你在標題中寫了「in C」,這是什麼? – Rakete1111

+0

道歉,這是一個錯誤輸入標籤,它是C(我編輯是正確的) –

+0

你的代碼甚至沒有編譯。 –

回答

2

,除非你在一個struct包裹它們不能從一個函數返回多個值。就指針而言,您可以修改從main傳遞給函數的值。我認爲你錯在這裏做:

scanf("%lf", &topSpeed); 

由於topSpeed是一個指向雙,你只需要通過從主傳遞的變量(不是指針變量的地址)的地址。而應該做的:

do { 
    printf("Please enter the top speed of the bugatti in km/h\n"); 
    scanf("%lf", topSpeed); 
} while(*topSpeed<=0); 
do { 
    printf("Please enter the year of the bugatti, in four digit form (e.g. 1999)\n"); 
    scanf("%lf", year); 
} while(*year<=0); 
do { 
    printf("Please enter the horsepower of the bugatti\n"); 
    scanf("%lf", horsepower); 
} while(*horsepower<=0); 

我希望這有助於。

1

你聲明的main函數中的變量tSyR & hP和參考get_positive_value()功能與他們擦肩而過。

因此地址的變量正在通過。不是變量本身。

get_positive_value(),要嘗試一些值放到使用scanf()你應該已經給變量的地址,但給了地址的地址,而不是3個變量。 &topSpeed in get_positive_value()就像&(&tS) in main()

既然你已經按引用傳遞它們,get_positive_value(),你有tSyRhP地址在topSpeedyearhorsepower分別。

topSpeed本身是tS的地址。不是&topSpeed

應更改
scanf("%lf", &topSpeed);

scanf("%lf", topSpeed);
(同樣對其他2個變量)

由於topSpeed是具有main()可變tS的地址。因此,如果您說&topSpeed您正嘗試訪問「地址tS」的地址。

0

當你這樣做 *someptr你正在要求的價值,在這個指針指向的內存地址。

當你做一個scanf並使用&x一個變量,你因爲要值存儲在內存地址做到這一點。因此,當您使用指針執行scanf時,您不使用*,因爲您傳遞值而不是地址,以將值存儲在。

您也不會使用&,因爲您傳遞指針的內存地址而不是實際想要修改的地址。這是你的主要錯誤。 最後,你可以使用struct同時使用return這些值,但指針更優雅。

希望我幫了你,我很清楚。