我試過 %.02d 和 d 來格式化數字資料格式,但它一直給我右邊的小數點后 6 位。我在互聯網上搜索過,但我一直得到相同的負數。請幫忙。這是我所擁有的:
/*
*Standard C libraries
*/
#include <stdio.h>
#include <string.h>
/*
* Custom Headers
*/
/*
*Declarations
*/
char mealChoice[100];
double total = 0.0;
double subTotal = 0.0;
double mealCost = 0.0;
const double HST = 0.15;
const double ECO_DEPOSIT = 0.10;
//void calcTotal();
//void displayMenu(void);
//double getOrder();
int main(int argc, char *argv[])
{
printf("There is one size of hot/cold beverage: 435ml\n\n");
printf("Choices for hot beverages are: tea, cappachino, coffee\n\n");
printf("Choices for cold beverages are: orange juice, milk, chocolate milk, bottled water\n\n");
printf("Food choices for Breakfast: eggs, ham, bacon, toast with jam, and hasbrowns");
printf("Food choices for Lunch: Pizza, lasagna, mac n cheese with bacon\n\n");
printf("Food Choices for Dinner: Fish n' chips, sub with onion rings, fries, poutine, shephards pie, chicken alfredo \n\n");
printf("Prices for Breakfast: $12.50, Lunch: $15.00 and Dinner $35.00\n");
printf("Enter the customer's choice of Meal \n\n");
gets(mealChoice);
printf("Enter the cost of meal: \n");
scanf("%lf", &mealCost);
subTotal = mealCost (mealCost * HST);
total = subTotal ECO_DEPOSIT;
printf("\nYour order: %s", mealChoice, "\n");
printf("\nTotal cost: $ %lf", total, "\n");
printf("\nThank you for your support!\n");
printf("Come again! \n");
return 0;
}
uj5u.com熱心網友回復:
您的代碼中存在一些問題:
- 永遠不要
gets()在您的任何程式中再次使用。fgets()是一個不錯的選擇。我建議你閱讀這篇文章。 - 除非你真的需要,否則避免使用全域變數。在你的情況下,你沒有。
- 決議
floats的正確格式說明符是s%f和s(如果我還記得的話%lf,doublelf 代表長浮點數)。 - 不要使用
doubles 或floats 來表示貨幣價值,因為它們不精確。在您的用例中,它可能不會產生影響,因為:(1)您正在處理少量資金,并且(2)您沒有做一些嚴肅的事情。但是對于生產代碼,沒有。見這里。
這是您的代碼的作業版本(使用doubles):
int main(void)
{
char mealChoice[100];
double total = 0.0;
double subTotal = 0.0;
double mealCost = 0.0;
const double HST = 0.15;
const double ECO_DEPOSIT = 0.10;
const char *menu =
"There is one size of hot/cold beverage: 435ml\n"
"Choices for hot beverages are: tea, cappachino, coffee\n"
"Choices for cold beverages are: orange juice, milk, chocolate milk, bottled water\n"
"Food choices for Breakfast: eggs, ham, bacon, toast with jam, and hasbrowns\n"
"Food choices for Lunch: Pizza, lasagna, mac n cheese with bacon\n"
"Food Choices for Dinner: Fish n' chips, sub with onion rings, fries, poutine, shephards pie, chicken alfredo\n"
"Prices for Breakfast: $12.50, Lunch: $15.00 and Dinner $35.00\n";
printf("%s\n", menu); // No need to call printf mutiple times.
printf("Enter the customer's choice of Meal: ");
get_string(mealChoice, sizeof mealChoice); // scanf("
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468825.html
標籤:C
上一篇:我的變數未在函式中宣告。c語言
