2017-04-16 204 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这些值,但指针更优雅。

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