2017-06-09 36 views
-1

我在程序中的目標是提示用戶在一定範圍內的金錢價值(浮動)以用於其他功能。但是,使用一組字符作爲輸入,其他函數似乎更容易完成。我研究過使用sprintf和snprintf,但不知道如何/如果這些可以用一個變量輸入而不是一個常量來實現。將變量用戶輸入float轉換爲C中的一個字符數組?

該號碼將被傳遞給該函數的函數需要將該號碼轉換爲文字。例如:1150.50 =一千五百美元和五十美分。

這是我試圖實現的代碼段;

do { 

     puts("Please enter the amount of the paycheck, this must be from 0$ to 10000$: \n"); 
     scanf("%.2f", entered_amount); 

     if (entered_amount < 0.00 && entered_amount > 10000.00) { 
     printf("This is not a valid amount, please try again! \n\n"); 

     } 

    } while (entered_amount < 0.00 && entered_amount > 10000.00); 

    sprintf(amount, "%f", entered_amount);     
    //Trying to convert a float entered by the user to an array of characters to use in the number_to_word function! 
    printf("%s", amount); 

凡entered_amount將用戶輸入浮子,和量將是 陣列炭的的。例如: 5555.55 = {「5,5,5,5,。,5,5」}

感謝所有幫助和反饋,謝謝!

+1

1)'entered_amount <0.00 && entered_amount> 10000.00) ' - >'entered_amount <0.00 || entered_amount> 10000.00)' – BLUEPIXY

+0

啊,很好的接受,謝謝! – Douggle07

+1

'scanf(「%。2f」,entered_amount);'... emmm..missing a'&'somewhere? –

回答

0

如果amount是足夠大小的char數組,那麼在調用sprintf之後,就會得到所需的結構。

sprintf(amount, "%f", entered_amount); 

按照您的嘗試,您可以通過printf輕鬆打印。

printf("%s", amount); //Print entire array 
//Print char by char 
size_t i = 0; 
for (i = 0; i < strlen(amount); i++) 
    printf("%c", amount[i]); 

的問題更與檢查範圍內的if語句。

if (entered_amount < 0.00 && entered_amount > 10000.00) { 

這永遠不會被執行。用這個代替:

if (entered_amount < 0.00 || entered_amount > 10000.00) { 

閱讀時浮,你應該通過指針做(檢查額外&字符):

scanf("%.2f", &entered_amount); 
+0

嗯,我修正了||而不是在while循環中的&&,以及&entered_amount。真正的問題是sprintf(金額,「%f」,entered_amount),當我printf(「%s」,金額)它只打印0.00000..regardless輸入的值。 – Douggle07

相關問題