从命令行获取双参数
这是一个简单的程序,它在 C 中将华氏度转换为摄氏度,它扫描华氏度的输入,这很好,但我想直接从终端获取参数,因此
将使用预期行为./temperature.c 40,预期输出将是40.00 Fahrenheit is equal to 4.44 Celsius
int main(int argc, double argv[])
{
double celsius;
double fahrenheit;
fahrenheit = argv[1];
printf("Enter the temperature here in Fahrenheit: ");
/* scanf("%lf", &fahrenheit);*/
celsius = (fahrenheit - 32) * 5 / 9 ;
printf("%.2lf fahrenheit is equal to %.2lf celsiusn", fahrenheit, celsius);
return 0;
}
回答
您必须声明argv为char* argv[](您从命令行获得一个字符串指针数组)。从那里,您可以使用函数将字符串转换为双精度值,例如strtod.
ps:您应该检查用户是否实际从命令行指定了您期望的温度:
int main(int argc, char* argv[])
{
if(argc < 2)
{
fprintf(stderr, "usage : %s <temperature in fahrenheit>", argv[0]);
return 0;
}
else
{
// convert argv[1] to double
}
// ...
return 0;
}
- i.e. automatic conversion of command line parameters to other types is not possible.