![](/img/trans.png)
[英]How to use scanf to read inputs which are in the form of float1##float2 (i.e., two float numbers separated by two pound signs)
[英]How to use scanf to read a number declared as float?
#include <stdio.h>
int main() {
float initialPrice, discount, VAT, priceWithVAT, priceWithDiscount;
initialPrice = 13.26;
VAT = 0.20;
discount = 0.125;
priceWithVAT = initialPrice * (1.0 + VAT);
priceWithDiscount = priceWithVAT * (1.0 - discount);
printf("Initial Price %10.2f\n", initialPrice);
printf(" + VAT @ %4.1f%% %10.2f\n", VAT * 100, priceWithVAT);
printf(" - discount @ %4.1f%%%10.2f\n", discount * 100, priceWithDiscount);
return 0;
}
我是 C 編程的新手,並被要求修改上述程序,以便它在進行計算之前使用 scanf 讀取初始價格。
我需要做什么?
謝謝
要將浮點數讀入initialPrice
變量,我們應該首先看看scanf
是如何工作的。 正如您在此處看到的, scanf
具有簽名:
int scanf(const char *format, ...)
format
參數是一個帶有“格式字符串”的字符串,您可以觀察到格式字符串或多或少由%[chars][type]
,其中[chars]
是應該讀取的最大[chars]
數和[type]
是一組表示參數類型的字符。 在這種情況下,我們不關心輸入大小,我們想讀入一個浮點數,所以我們使用格式字符串%f
。 現在我們需要提供我們想要讀入的變量的地址作為下一個參數,所以我們使用&
字符來獲取initialPrice
的地址。 這非常重要,因為沒有&
,代碼將導致分段錯誤。 所以,我們的最后一行看起來像
scanf("%f", &initialPrice);
請注意,在要求輸入之前打印某種提示是一個好習慣,並且您應該檢查scanf
的返回值以確保它等於 1,因為這是您想要讀入的變量數量。
這看起來像是一項家庭作業,因此最好由您自己提出解決方案。
不是將 initialPrice 設置為 13.26,而是添加一行代碼,調用 scanf 將 initialPrice 的值設置為某物。 scanf 需要將一些消息傳遞給用戶以及 initialPrice 變量以存儲用戶輸入的任何內容。
printf("請輸入初始價格值\\n"); scanf("%f\\n",& InitialPrice); 您可以通過添加這幾行來編輯您的,並且不要將任何值初始化為“initialPrice = 13.26;” 因為它會取那個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.