c - 根据用户输入查找插值

标签 c function char interpolation do-while

我对算法做了一些修改,并在函数中获取了一个值(虽然不正确),但返回值拒绝将其发送回主函数。另外,我无法得到要求程序重新运行以发挥作用的代码部分。

#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的原因是

getdistance(time_arr, distance_arr, usertime, maxtime);

int main()函数中,您调用函数getdistance来计算插值值并返回该值,但在main函数中返回值没有分配给变量插值。所以你必须将代码修改为

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

这将打印输出

关于c - 根据用户输入查找插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22776518/

相关文章:

c++ - 我应该使用哪种数据类型在 C++ 的变量中存储最多 18 位数字?

c - UDP 接收不成功

在 R 中创建数据帧的再现函数 - 可再现代码

php - 如何使用 PHP 的 mail() 函数发送电子邮件

C++ 全局字符指针?

C编程,[错误]调用对象 'swap'不是函数或函数指针

c - C 中的运行时多态性

php - 如何添加 woocommerce 自定义订单状态?

c++ - for 循环写特殊符号

c++ - 缓存 const char * 作为返回类型