質問

I made some revisions to the algorithm, and get a value (though it is incorrect) in the function, but the return value refuses to send it back to the main function. Also, I cannot get they yes no portion of the code that ask for the program to rerun to function.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
/*Prototype for functions used*/
float getdistance(float[], float[], float, int);
float printvalue(float);

int main()
{

      int maxtime = 18;
      float usertime = 0;
      char reiteration;
      char y, n;
      int reit_choice = 0;
      float interpolation = 0.0;
      float time_arr[]={0,3,5,8,10,12,15,18};
      float distance_arr[]={2,5.2,6,10,10.4,13.4,14.8,18};
      do
      { 
       printf("Please enter a number between 0 and 18 for the starting time:");
       scanf("%f", &usertime, "\b");
        while(usertime <0 || usertime >18)
       {
          printf("The value you have entered is not valid, please enter a value between 1 and 18");
          scanf("%f", &usertime, "\b");
       }/*End of data verification loop*/
       getdistance(time_arr, distance_arr, usertime, maxtime);
       printf("%f", interpolation);
       printvalue(interpolation);

       system("pause");

       printf("would you like to check another time?(y/n)");
       scanf("%c[y n]", &reiteration, "\b");
       while(reiteration!='y' || reiteration!='n')
       {
          printf("Please enter either y for yes or n for no");
          scanf("%c", &reiteration, "\b");
       }/*End of choice verification loop*/
       if(reiteration = 'y')
       {
         reit_choice = 1;
       }
       else
       {
         reit_choice = 0;
       }
}/*End of do loop*/
while(reit_choice);

}/*End of main loop*/

float getdistance(float time_arr[], float distance_arr[], float usertime, int maxtime)
{
   int index=0;
   float interpolation = 0;

   for(index; usertime > time_arr[index]; index++)
   {
      if(usertime<3)
      {
         break;
      }
   }/*End of value assignment for loop*/
   interpolation = (time_arr[index]) + (((time_arr[index +1] -     time_arr[index])/(distance_arr[index +1] - distance_arr[index])) * (usertime - distance_arr[index]));
   printf("%f", interpolation);
   return interpolation;
}/*End of distance calculation loop*/

float printvalue(float interpolation)
{
   printf("The interpolation was %f", interpolation);
}/*End of screen print loop*/
役に立ちましたか?

解決

The reason for 0 output is

getdistance(time_arr, distance_arr, usertime, maxtime);

in int main() function you're calling the function getdistance which calculates the interpolation value and returns the value, But in main function the returned value is not assigned to the variable interpolation . so you've to modify the code as

interpolation = getdistance(time_arr, distance_arr, usertime, maxtime);
printvalue(interpolation);

Which will print the output

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top