【发布时间】:2025-11-25 01:15:01
【问题描述】:
我从书中逐字输入了以下代码:
// Ex program #2 from Ch 8 of ABGTC
// File Ch8Ex2.c
// This is a sample program that asks users for some basic data and prints it on screen in order to show what was entered
#include <stdio.h>
main()
{
float cost;
char topping[24];
int slices;
int month, day, year;
// The first scanf will look for a floating-point variable, the cost of a pizza
// If the user doesn't enter a $ before the cost, it could cause problems
printf("How much does a pizza cost in your area? Enter as $XX.XX\n");
scanf(" $%f", &cost);
// The pizza topping is a string, so your scanf doesn't need an &
printf("What is your favorite one-word pizza topping?\n");
scanf(" %s", topping);
printf("How many slices of %s pizza can you eat in one sitting?", topping);
scanf(" %d", &slices);
printf("What is today\'s date (enter it in XX/XX/XX format).\n");
scanf(" %d/%d/%d", &month, &day, &year);
printf("\n\nWhy not treat yourself to a dinner on %d/%d/%d", month, day, year);
printf("\nand have %d slices of %s pizza!\n", slices, topping);
printf("It will only cost you $%.2f!\n\n\n", cost);
return 0;
}
编译时出现零错误(使用代码:块,如书中推荐和使用的那样);然而,一旦我运行程序,在输入请求的用户数据的第一位(一片披萨的价格,假设我说它是 03.45)后,程序就会打印出来:
"What is your favorite one-word pizza topping?"
"How many slices of 03.45 pizza can you eat in one sitting?"
感觉就像是跳过了 printf "What is your favorite...." 后面的 scanf 行,不仅提示了 "How many slices...." 后面的 printf 行,而是插入了 03.45 作为应该由用户在上一行输入的字符数组/字符串值。
我尝试了一些不同的调整,但我终其一生都无法弄清楚我做错了什么。有任何想法吗?
【问题讨论】:
-
您显示的源代码真的是正在运行的代码吗?如果您看到输出,它与代码应该执行的操作不对应(将价格打印为字符串?)。程序的 full 输出是什么?程序的实际输入是什么?
-
我展示的源代码实际上是正在运行的代码。我可以说它不对应。以下是我运行程序时发生的情况:“你所在地区的比萨饼要多少钱?”这是第一个问题,我输入 03.45 并回车。然后我在屏幕上看到以下内容:“你最喜欢的单字披萨配料是什么?” “你一次可以吃多少片03.45披萨?”是不是更详细一点?
-
您缺少前导“$”。您必须输入如下内容:
$03.45,正如问题所问(输入为 $XX.XX) -
^ 这就是整个问题.....哦,天哪,哈哈哈,谢谢 Amadeus!
-
@GuyWantingBoat:你能接受其中一个答案吗?