簡體   English   中英

k&r示例,溫度轉換

[英]k&r example, temperature conversion

我在玩K&R中的一些代碼只是為了好玩,但遇到了一個我無法解釋的錯誤。 我正在修改第1.2頁第9頁的代碼,即溫度轉換程序:

#include <stdio.h>
/* converts a range of fahrenheit temperatures to celsius
and displays them in a table*/

int main(int argc, char *argv[]){
  float fahr, celsius;
  float lower, upper, step;

  if(argc != 4){
    printf("Usage: ./tempConvert lower upper step\n");
    return 1;
  }

  // note: atof is bad?
  lower = atof(argv[1]);   // lower limit of temperature
  upper = atof(argv[2]);   // upper limit of temperature
  step  = atof(argv[3]);   // step size

  //printf("%f %f %f",lower, upper, step);

  fahr = lower;
  printf("F \t C \n");

  while(fahr <= upper){
    celsius = 5.0*(fahr-32.0)/9.0; // if this were int, 5/9=0 because int division
    printf("%3.1f \t %6.1f\n", fahr, celsius);
    fahr += step;
  }

  return 0;
}

運行時,出現無限循環。 但是,當我將atof更改為atoi時,除了我想要浮點精度而不是僅使用整數這一事實之外,它的工作效果非常好。 在輸入值之后立即打印出這些值也會產生垃圾,而不是我輸入的數字。 是什么導致使用atoi和atof讀取數字之間的差異?

您沒有包含<stdlib.h> ,因此您的編譯器假定atof()返回一個int ,但沒有。

您沒有啟用足夠的警告進行編譯! 您應該堅持要求編譯器在調用范圍內沒有原型的函數時警告您。 請注意,如果該函數根本沒有聲明,則C99模式會警告您,但它仍允許使用非原型聲明。

在GCC中,我通常使用此命令(或-std=c11和其他選項):

gcc -g -O3 -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
    -Wold-style-definition -Wold-style-declaration -Werror ...

您的代碼將無法在這些選項下進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM