我试图获取用户输入,这是一个字符串,并将其转换为浮点数。就我而言,当用户输入gas
时,55.000000
会一直打印为7
- 我希望将其打印为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;
}
答案 0 :(得分:1)
为什么不这样做?它简单得多。
#include<stdio.h>
int main()
{
int gas;
printf("Please enter the number of gallons of gasoline.\n : ");
//use the %d specifier to get an integer. This is more direct.
//It will also allow the user to order more than 9 gallons of gas.
scanf("%d", &gas);
printf("\nHello %d", gas);//prints integer value of gas
//Using the .1f allows you to get one place beyond the decimal
//so you get the .0 after the integer entered.
printf("\nHello %.1f\n", (float) gas);//print floating point
return 0;
}
答案 1 :(得分:1)
你说:
就我而言,当用户输入
时,气体会一直打印为55.000000
7
当用户输入7
作为输入时,数字7
将存储为gas_gallons
中的字符。 ASCII编码中字符7
的十进制值为55
。您可以在Wikipedia以及网络上的许多其他位置查看ASCII编码中其他字符的十进制值。
使用时:
gas = gas_gallons;
gas_gallons
的整数值,即55,被分配给gas
。这就解释了为什么在打印55.000000
时将gas
作为输出。
您可以通过多种方式解决问题。以下是一些建议。
选项1
使用以下方法将数字转换为数字:
gas = gas_gallons - '0';
选项2
丢弃代码以读取汽油加仑数作为数字并将数字转换为数字。使用数字也是有限制的,因为您不能将10
或12.5
作为输入。
直接读取加仑汽油的数量。使用此方法,您的输入可以是任何浮点数,可以用float
表示。
#include <stdio.h>
int main()
{
float num_gallons;
while ( 1 )
{
printf("Please enter the number of gallons of gasoline: ");
// Read the number of gallons of gas.
// If reading is successful, break of the loop.
if (scanf("%f", &num_gallons) == 1 )
{
break;
}
// There was an error.
// Read and discard the rest of the line in the input
// stream.
scanf("%*[^\n]%*c");
printf("There was an error in reading the gallons of gasoline.\n");
}
printf("\nHello %f\n", num_gallons);
return 0;
}
答案 2 :(得分:0)
ASCII字符'0'
- '9'
没有0-9的整数值。您可以通过减去'0'
找到适当的值。
答案 3 :(得分:0)
要将字符串转换为float,您可以使用atof
中包含的stdlib.h
(ASCII到float)函数。
以下是此函数的完整声明:double atof(const char *str)
所以你可以做一个简单的演员
gas = (float) atof(gas_gallons);