这是我第一次编程,我迷路了。我正在尝试执行此数学运算,但是它会不断出错,并且我不确定问题出在哪里。另外,我不知道如何将所有数字输出都放在小数点后两位。请帮忙。这是我到目前为止所说的。

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*句柄作为第一个参数。要在输出中使用两位小数,只需在%.02f中使用printf()/fprint()

另请参见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;
}


将输出:


  汽车在7.50小时内行驶425.50英里,行驶速度为56.73
  每小时该汽车总共行驶了680800.00米,时速189.11
  米每秒。

10-04 13:26