华氏度到摄氏度的程序改进和选择输出
我几天前刚开始用C语言编程,我想改进我的程序,但不知道该怎么做。
该程序是华氏温度到摄氏温度,反之亦然。 我用最简单的方式做到了。 但现在我想这样做,以便我有2个函数c2f和f2c,它们将温度作为参数,当我运行程序时,我想要选择是否要从F转换为C或从C转换为F(类似于TempConverter -f 32这应该只将32转换为摄氏温度,TempConverter -c 100应该将100转换为华氏温度)。
我认为我的函数应该是这样的: float c2f(float c)和float f2c(float f)
但是它究竟是如何做到这一点所以当我运行类似> TempConverter -f 50.0的东西时,我会得到类似这样的东西吗? 10.00°C = 50.00°F
#include int main(void) { // Local Declarations float Celsius, Fahrenheit, Fahrenheit_1, Celsius_2; // Statements printf("Enter the temperature in Fahrenheit: "); scanf("%f", &Fahrenheit); printf("Fahrenheit temperature is: %5.1f F\n\a", Fahrenheit); Celsius = (100.0 / 180.0) * (Fahrenheit - 32); printf("Celsius temperature is: %8.1f C\n\n\a", Celsius); printf("Enter the temperature in Celsius: "); scanf("%f", &Celsius_2); printf("Celsius temperature is: %8.1f C\n\a", Celsius_2); Fahrenheit_1 = 32 + (Celsius_2 * (180.0 / 100.0)); printf("Fahrenheit temperature is: %5.1f F\a", Fahrenheit_1); return 0; }
当前输出:
*输入华氏温度:20
华氏温度为:20.0 F.
摄氏温度为:-6.7℃
以摄氏度输入温度:40
摄氏温度为:40.0℃
华氏温度:104.0 F *
期望的输出
TempConverter -f 50.0
10.00°C = 50.00°F
您需要做的第一件事是在代码中添加命令行参数,如下所示:
int main( int argc, char **argv )
argc
包含在命令行中输入的参数数量; 它总是> = 1。
argv
包含指向每个命令行参数字符串的指针。 argv[0]
总是指向用于启动程序的字符串。 argv[argc]
始终为NULL。
所以,如果你把你的程序称为
TempConverter -f 50.00
然后
argc == 3 argv[0] == "TempConverter" argv[1] == "-f" argv[2] == "50.00" argv[3] == NULL
请注意,要在转换函数中使用最后一个参数,您需要将其从字符串转换为浮点值。 strtod
是这个选择的库函数:
char *check; double intemp = strtod(argv[2], &check);
转换后, check
将指向字符串中未转换为浮点值的第一个字符。 如果此字符不是空格或0,则输入值不是有效的浮点字符串。
那么,一般的操作顺序:
- 检查
argc
的值。 为了您的目的,它需要是3。 - 使用
strtod
将argv[2]
转换为浮点值。 确保检查字符为0或空格。 - 检查您的华氏度/ celcius开关; 它需要是
"-f"
或"-c"
(或者你决定的任何东西)。 - 根据华氏度/ celcius开关调用相应的转换function,并显示结果。
您正在寻找使用命令行参数作为main
参数
int main(int argc, char *argv[])
这里argc
对应于提供的参数数量,参数存储在argv
。 请注意,程序的名称也被视为参数,并存储在argv[0]
。 假设你期望一个标志-f
或-c
后跟一个float
,你可以在main
使用它们,如下所示:
/** * Check for the expected number of arguments (3) * (0) program name * (1) flag * (2) temperature */ if (argc!=3) printf("Incorrect number of arguments"); if (!strcmp(argv[1], "-f")) // process from fahrenheit to celsius else if (!strcmp(argv[1], "-c")) // process from celsius to fahrenheit else printf("Invalid flag\n");
请注意,每当您处理用户输入时, 检查输入是否符合您的预期非常重要。 我建议的代码提供了一些示例,但您应该认真考虑如何使其更安全
#include main(int argc,char** argv) { int result; printf("\nValue of Celcius: \n"); scanf("%i", &argc); printf("\n%i Celcius = ", argc); result = ((argc * 9) /5) + 32; printf("%i Fahrenheit\n", result); getchar(); getchar(); return 0; }