我对算法进行了一些修改,并在函数中获取了一个值(尽管它是不正确的),但返回值拒绝将其发送回main函数。此外,我不能得到它们是没有要求程序重新运行的代码部分。
#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*/
答案 0 :(得分:1)
0输出的原因是
getdistance(time_arr, distance_arr, usertime, maxtime);
在 int main()函数中你调用函数 getdistance 来计算插值并返回值,但在main函数中返回值未分配给变量插值。所以你可以修改代码
interpolation = getdistance(time_arr, distance_arr, usertime, maxtime);
printvalue(interpolation);
将打印输出