再會!我嘗試在我的第一個專案中使用 C 制作一個簡單的計算器,該專案涉及華氏與攝氏之間的轉換,反之亦然。但它不起作用,有人能告訴我我想念什么嗎?
這是我的代碼:
#include <stdio.h>
int main()
{
double temp, fahrenheit, celsius;
char answer[2];
printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
fgets(answer, 2, stdin);
fahrenheit = (temp * 1.8) 32;
celsius = (temp - 32) * 0.5556;
if(answer == "CF"){
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", fahrenheit);
}
else if(answer == "FC"){
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", celsius);
}
return 0;
}
計算器
uj5u.com熱心網友回復:
使用strcmp的
(answer == "CF"){
IE
strcmp(answer, "CF") == 0
uj5u.com熱心網友回復:
你不能在 C 中比較這樣的字串。那里strcmp和strncmp函式。除了這個 C 字串以\0符號結尾,所以你的代碼應該是這樣的:
#include <stdio.h>
#include <string.h>
int main()
{
double temp, fahrenheit, celsius;
char answer[3];
printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
fgets(answer, 3, stdin);
fahrenheit = (temp * 1.8) 32;
celsius = (temp - 32) * 0.5556;
if (strcmp(answer, "CF") == 0) {
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", fahrenheit);
} else if (strcmp(answer, "FC") == 0){
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", celsius);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/342441.html
