我試圖接受用戶輸入,這是一個字符串,並將其轉換爲浮點數。在我的情況下,當用戶輸入7
時,gas
不斷打印爲55.000000
- 我希望它被打印爲7.0
。將字符串轉換爲浮點數
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main()
{
char gas_gallons;
float gas;
printf("Please enter the number of gallons of gasoline: ");
scanf("%c", &gas_gallons);
while (!isdigit(gas_gallons))
{
printf("\nYou need to enter a digit. Please enter the number of gallons of gasoline: ");
scanf("%c", &gas_gallons);
}
if (isdigit(gas_gallons))
{
printf("\nHello %c", gas_gallons);
gas = gas_gallons;
printf("\nHello f", gas);
}
return 0;
}
錯字在最後的printf。並瞭解printf格式字符串語法。這將有所幫助。 – Olaf
你的輸入是一個字符,而不是「字符串」(如果這將存在於C中 - 你很可能意味着一個字符數組)。 – Olaf