2015-05-26 314 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);

相關問題