【问题标题】:Problems with outputting data into a text file将数据输出到文本文件的问题
【发布时间】:2013-01-07 17:32:39
【问题描述】:

我目前正在尝试构建一个程序来计算一个值,并将这些值输出到一个文本文件中。在编译时,我收到以下错误:

'ISO C90 禁止混合减速和代码'

我的编译器是 Quincy 2005,它将第 11 行 (int f=10;) 标记为问题:

#include <stdio.h>


int main()

{

FILE *output;
output = fopen("inductor.txt","a+");

int f=10;
float l, ir, realir;

printf("What is your inductor value (mH)\n");
scanf("%f", &l);

  while (f< 10000000){
  ir=((2*3.141)*f*l);
  realir = ir/1000;

  printf("If Frequency = %d Hz" ,f);
  printf(" Inductive reactance= %f Ohms\n",realir);

  fprintf(output, "%d Hz : %f Ohms\n ", f, realir);


 f=f*10;

 }

fclose(output);

return 0;
}

令人讨厌的是,更改编译器不是一种选择。

【问题讨论】:

  • 您是否不清楚错误消息?它准确地说明了问题所在。你说你不能改变编译器,但听起来你的编译器确实支持混合声明和代码,你只需要将它切换到另一种模式(可能是C99)。
  • 注意:“减速”!=“声明”。

标签: c output text-files


【解决方案1】:

我相信它是说您需要先声明所有变量,然后再声明代码。

例如:

FILE *output;
int f=10;
float l, ir, realir;


output = fopen("inductor.txt","a+");
printf("What is your inductor value (mH)\n");

【讨论】:

    【解决方案2】:

    output = fopen("inductor.txt","a+"); 移至其他变量声明的下方。您必须先声明所有变量,然后再使用它们。

    【讨论】:

      【解决方案3】:

      根据之前的答案,有两种方法可以否定这一点,因为 ISO C90 不允许混合变量声明和代码。 已经提到了一种方法:按照建议移动变量声明。

      FILE *output;
      int f=10;
      float l, ir, realir;
      output = fopen("inductor.txt","a+");
      // More code
      

      还有另一种方法。根据 ISO C90,您只能在代码块打开 { 之后在代码中声明一个变量。由于您可以随时引入代码块,如果您不想过多地更改代码,您可以简单地启动一个块并将代码放在那里。请注意,以这种方式声明的变量仅在包含它们的块内有效。我强烈推荐第一个选项。

      FILE *output;
      output = fopen("inductor.txt","a+");
      {
      int f=10;
      float l, ir, realir;
      // More code on this variables.
      }
      // Variables declared in the block previously will not be valid here.
      

      【讨论】:

      • 在选项二中,变量仅在 {} 块内有效。所以它不会起作用。
      • 是的,谢谢你。我编辑了我的问题以反映这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多