我试图接受用户输入,这是一个字符串,并将其转换为浮点数。在我的情况下,当用户输入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