使用浮点算术,而不是整数算术,因为在整数算术中,5/9 为 0。所以您可以对代码进行此更改(尽管float
参数不常见):
float f2c(float f)
{
return (f - 32.0) * 5.0/9.0;
}
float c2f(float c)
{
return 9.0 * c/5.0 + 32.0;
}
同样作为其他答案之一,条件(&ch == "-f")
永远不会成立。
这是一个完整的工作示例,带有错误检查。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
#include <assert.h>
static double f2c(double f)
{
return (f - 32.0) * 5.0/9.0;
}
static double c2f(double c)
{
return 9.0 * c/5.0 + 32.0;
}
int main (int argc, char *argv[])
{
int i;
const char *label_f = "Fahrenheit";
const char *label_c = "Celcius";
const char *from, *to;
double (*conversion)(double);
from = label_c;
to = label_f;
conversion = c2f;
for (i=1; i<argc; ++i)
{
if (0 == strcmp(argv[i], "-f"))
{
from = label_f;
to = label_c;
conversion = f2c;
}
else if (0 == strcmp(argv[i], "-c"))
{
from = label_c;
to = label_f;
conversion = c2f;
}
else
{
char *suffix = NULL;
double temp_in;
errno = 0;
temp_in = strtod(argv[i], &suffix);
if (ERANGE == errno)
{
if (HUGE_VAL == temp_in)
{
fprintf(stderr, "%s is too big", argv[i]);
return 1;
}
else
{
assert(-HUGE_VAL == temp_in);
fprintf(stderr, "%s is too small", argv[i]);
return 1;
}
}
else if (errno != 0 && (suffix == argv[i]))
{
/* no conversion was performed. */
fprintf(stderr, "%s is not a number", argv[i]);
return 1;
}
else if (*suffix)
{
fprintf(stderr, "Expected a number but saw '%s'\n", argv[i]);
return 1;
}
else
{
const double temp_out = (*conversion)(temp_in);
printf("%f %s is %f %s.\n", temp_in, from, temp_out, to);
}
}
}
return 0;
}