【问题标题】:Error regarding Float & Int in C MethodC 方法中有关 Float 和 Int 的错误
【发布时间】:2015-04-16 11:31:21
【问题描述】:

所以我正在尝试用 C 语言编写一个带有方法的基本程序,但在编译程序时不断出错,这是由于我的方法所致

我不断收到错误提示

curve.c: In function ‘compute_curve’:
curve.c:32:7: error: argument ‘f’ doesn’t match prototype
 float compute_curve(f)
       ^
curve.c:6:7: error: prototype declaration
float compute_curve(float);

我是这个编译的新手,所以只是好奇我在哪里搞砸了 float 和 int 的

【问题讨论】:

  • main() 应该是 int main(void)float compute_curve(f) 应该是 float compute_curve(float f) 了解如何让你的编译器警告你这些事情。此外,C 函数不称为“方法”。它们被称为“函数”。
  • 还有一个没有提到的bug; fclose(fp); 应该在它所在的循环之外。(否则你在第一次迭代后关闭文件)。
  • 关于这一行:'float f = 1.0;' '1.0' 定义了一个 double,然后必须将其转换为 float 才能分配给 'f'。建议使用'float f = 1.0f;'其中最后的 'f' 是一个值修饰符,它使值变为浮点数
  • 在处理浮点值时,您需要非常小心使用“=”,因为许多数字不能完全用浮点数或双精度数实现。
  • 这一行:'while (f != 0)' 将浮点值与整数值进行比较。建议使用:'while (f != 0.0f)'

标签: c methods compilation int


【解决方案1】:

你的原型也需要像float compute_curve(float x)一样声明一个变量名,你的实际实现定义也应该匹配。

【讨论】:

    【解决方案2】:
    float compute_curve(float f)
    

    f 本身没有命名类型,“float”有。原型使用“float”,这让你的编译器给你一个关于不匹配声明的错误,而不是“f”不是一个类型,我假设。

    【讨论】:

      【解决方案3】:

      这是编译器提出的重要警告(需要修复)

      在函数中:main() -- 返回类型默认为int

      在函数中:compute_curve() -- 参数 'f' 默认为 int -- 参数“f”与原型不匹配 -- 控制到达非空函数的结尾

      下面是代码的样子

      (带有适当的缩进和错误检查)

      #include <stdio.h>
      #include <stdlib.h>
      FILE *fp;
      
      
      void compute_curve(float);
      
      int main()
      {
          float f = 1.0f;
      
          if(NULL == (fp = fopen("Curve", "w") ) )
          { // then, fopen failed
              perror( "fopen for Curve failed");
              exit( EXIT_FAILURE );
          }
      
          // implied else, fopen successful
      
          printf("Hello");
      
          while (f != 0.0f)
          {
              printf("Input a Float value(0 to quit): ");
              if( 1 != (scanf("%f", &f) ) )
              { // scanf failed
                  perror( "scanf for float value failed" );
                  fclose( fp ); // cleanup
                  exit( EXIT_FAILURE );
              }
      
              // implied else, scanf successful
      
              compute_curve(f);
          } // end while
      
          fclose(fp); // cleanup
          return 0;
      } // end function: main
      
      
      void compute_curve(float f)
      {
          int n;
      
          for (n = 0; n<4096; n *= 2)
          {
              float Speedup = 1.0f / (( 1.0f - f ) + (f / (float)n));
              fprintf(fp, "%d\n",n) ;
              fprintf(fp, "%f\n", Speedup) ;
          } // end for
      } // end function: compute_curve
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        相关资源
        最近更新 更多