将字符串转换为浮点

时间:2015-05-26 23:55:22

标签: c casting floating-point-conversion

我试图获取用户输入,这是一个字符串,并将其转换为浮点数。就我而言,当用户输入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;
}

4 个答案:

答案 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

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

答案 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);