2015-05-26 221 views
1

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

错字在最后的printf。并了解printf格式字符串语法。这将有所帮助。 – Olaf

+0

你的输入是一个字符,而不是“字符串”(如果这将存在于C中 - 你很可能意味着一个字符数组)。 – Olaf

回答

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; 
} 
+0

他希望'gas'是'float',而不是'int'。但总体思路是正确的; '%c'不是要使用的正确格式。尽管如此,一个整数可能更有意义,但你应该解释你所做的改变,而不是简单地做出改变。 –

0

的ASCII字符'0' - '9'没有整数值0-9。您可以通过减去'0'找到合适的值。

+0

明白了!谢谢!!!! –

1

你说:

在我的情况,气体保持被印刷为55.000000当用户当用户进入7作为输入数字7被存储为在该字符输入7

gas_gallons。 ASCII编码的字符7的十进制值为55。您可以在Wikipedia和网络上的其他许多地方以ASCII编码的方式查看其他字符的十进制值。

当使用:

gas = gas_gallons; 

gas_gallons整数值是,即55,被分配给gas。这就解释了为什么当你打印gas时你得到55.000000作为输出。

您可以通过多种方式解决问题。这里有几个建议。

选项1

通过使用转换的数字到一个数字:

gas = gas_gallons - '0'; 

选项2

丢弃代码来读取加仑汽油的数量作为数字并将该数字转换为数字。使用数字也是有限制的,因为您不能使用1012.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; 
} 
0

要字符串转换为浮动您可以使用atof(ASCII浮动)列入stdlib.h功能。 下面是这个函数的完整声明:double atof(const char *str) 所以你可以做一个简单的投 gas = (float) atof(gas_gallons);

相关问题