【问题标题】:Write a program using a loop that outputs the following program使用输出以下程序的循环编写程序
【发布时间】:2017-06-17 19:03:48
【问题描述】:

所以我编写了一个程序,将度数转换为弧度,然后将结果作为输出打印出来。

 CODE (website not phone friendly)
 #include <stdio.h>
 #define PI 3.141593
 int main (){
     int degrees =10;
     double radians;
     printf("Degrees to Radians \n");

     while( degrees <= 360){
         radians = degrees*PI/180;
         printf("%6i %9.6f \n", degrees, radians);
        degrees +=10;
     }
 }
 END CODE

所以我希望能够使这个程序成为我的程序创建的实际输出。我有人向我建议 fprintf 但他们没有详细说明。我是 c 编程的新手,谁能解释我如何使用 fprintf (也许是广义的想法?)。我知道 fprint 是另一种打印输出的方式,但仅此而已。

【问题讨论】:

  • 打印到stdout? fprintf() 可能有点矫枉过正。
  • 你知道如何使用转义序列吗?在字符串文字 ("this is a string literal") 中,\n 表示换行符,\" 表示双引号,\\ 表示反斜杠。利用这些表示可以让您将代码表示为字符串文字,然后您可以像其他任何内容一样打印(使用putsprintf 或...)。

标签: c printf output


【解决方案1】:

以下是在代码中使用fprintf 的方法

int main() {
    FILE * fp;
     int degrees =10;
     double radians;
     printf("Degrees to Radians \n");
    fp = fopen("radians.txt","w+");
     while( degrees <= 360){
         radians = degrees*PI/180;
         printf("%6i %9.6f \n", degrees, radians);
         fprintf(fp, "%6i\t%9.6f \n", degrees, radians);
        degrees +=10;
     }
    return 0;
}

在这里,我在 fprintf 中添加了 \t 以获得一个制表符空间。 fopen 中的"w+" 将创建具有给定名称的新文件,因此您的所有输出都将保存在一个文件中。

【讨论】:

  • 我试过了,但我真正想做的是让程序成为输出。这样当我运行程序时,实际输出的是上面的程序,而不是度数到弧度的转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 2014-12-28
相关资源
最近更新 更多