c - 数学运算?

标签 c math decimal

这是我第一次编程,我迷失了。我正在尝试做这个数学运算,但它总是出错,我不确定问题出在哪里。另外,我不知道如何将所有数字输出保留两位小数。请帮忙。这就是我到目前为止所讲的内容。

int main(void) {
    int distance, time, speed, meters, mts_per_mile, sec_per_mile, mts, mps;
    csis = fopen("csis.txt", "w");

    distance = 425.5;
    time = 7.5;
    speed = distance / time;
    mts_per_mile = 1600;
    sec_per_mile = 3600;
    mts = distance * mts_per_mile;
    mps = mts / sec_per_mile;


    printf("The car going %d miles in %d hours is going at a speed of %d mph.\n", distance, time, speed);
    fprintf("The car going %d miles in %d hours is going at a speed of %d mph.\n", distance, time, speed);
    printf("The car has traveled %d meters total, at a rate of %d meters per second.", mts, mps);
    fprintf("The car has traveled %d meters total, at a rate of %d meters per second.", mts, mps);
    fclose(csis);
    return 0;
}

最佳答案

如果要使用 2 位小数,则需要使用 double 或 float 变量。此外,您还忘记提及 csis 变量的类型(即 FILE*)。 fprintf() 将您错过的 FILE* 句柄作为第一个参数。要在输出中使用两位小数,只需在 printf()/fprint() 中使用 %.02f 即可。

另请参阅 printf() 的引用和 fprintf()

#include <cstdlib>
#include <cstdio>

int main(void) {
  double distance, time, speed, mts_per_mile, sec_per_mile, mts, mps;
  FILE* csis = fopen("csis.txt", "w");

  distance = 425.5;
  time = 7.5;
  speed = distance / time;
  mts_per_mile = 1600;
  sec_per_mile = 3600;
  mts = distance * mts_per_mile;
  mps = mts / sec_per_mile;

  printf("The car going %.02f miles in %.02f hours is going at a speed of %.02f mph.\n", distance, time, speed);
  fprintf(csis, "The car going %.02f miles in %.02f hours is going at a speed of %.02f mph.\n", distance, time, speed);
  printf("The car has traveled %.02f meters total, at a rate of %.02f meters per second.", mts, mps);
  fprintf(csis, "The car has traveled %.02f meters total, at a rate of %.02f meters per second.", mts, mps);
  fclose(csis);
  return 0;
}

将输出:

The car going 425.50 miles in 7.50 hours is going at a speed of 56.73 mph. The car has traveled 680800.00 meters total, at a rate of 189.11 meters per second.

关于c - 数学运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216453/

相关文章:

C 长度间距

c - C中函数和变量的内存分配

转换说明符 %ju

c++ - 尾随空格是什么意思,它与空白有什么区别?

math - float 学坏了吗?

math - 非功能线的线性回归/寻线

具有最少小数位数的 Python 格式小数

c++ - 点到直线的正交投影

c# - 如何防止 C# 端的 SQL 舍入小数 (18,4) 输出

objective-c - 将十进制数转换为二进制 Objective-C