【发布时间】:2019-09-19 05:25:30
【问题描述】:
我是 C 编码(以及一般编码)的新手,所以我一直在练习一些随机程序。这个应该根据用户的年龄和所需的“区域”数量(他们想去多远)来确定交通票的成本(Translink Vancouver 价格)。我已经成功编译它,但由于某种我无法弄清楚的原因,scanf 函数被忽略了。我该如何解决?请记住,我只编码了几天。谢谢!
int main(void) {
int zones;
int age;
double price = 0.00;
printf("Welcome to TransLink cost calculator!\n\n");
printf("Please enter the desired number of zones (1, 2, or 3) you wish to travel: ");
scanf("%d", &zones);
if (zones < 1) {
printf("Invalid entry\n");
price = 0.00;
}
else if (zones > 3) {
printf("Invalid entry\n");
price = 0.00;
}
else if (zones == 1) {
printf("Please enter your age: ");
scanf("%d", &age);
if (age < 0.00) {
printf("Invalid Aage");
}
else if (age < 5) {
price = 1.95;
}
else if (age >= 5) {
price = 3.00;
}
}
else if (zones == 2) {
printf("Please enter your age: ");
scanf("%d", &age);
if (age < 0) {
printf("Invalid Aage");
}
else if (age < 5) {
price = 2.95;
}
else if (age >= 5) {
price = 4.25;
}
}
else if (zones == 3) {
printf("Please enter your age: ");
scanf("%d", &age);
if (age < 0) {
printf("Invalid Aage");
}
else if (age < 5) {
price = 3.95;
}
else if (age >= 5) {
price = 4.75;
}
}
printf("The price of your ticket is: $%.2f + tax\n", price);
system("PAUSE");
return 0;
}
【问题讨论】:
-
请解释您如何使用此调用
scanf("%d", &age);返回的值。不是扫描到age中的值,而是该调用返回的值。告诉您扫描是否成功的值。如果你不能,那么你就有了问题的答案。 -
感谢您的回复,但我不明白您想说什么。我不确定为什么它不起作用(因此我在这里发帖)所以如果你知道我可以如何解决它并告诉我那会很棒,谢谢。
-
顺便说一句。这不是问题,但年龄是一个 int 并且您正在与一个浮点常量进行比较: if (age
-
scanf()返回处理的值的数量。您应该将此与您尝试读取的变量数量进行比较,以确保它成功。例如if (scanf("%d", &age) != 1) { // print error message } -
无论你做了什么让 Visual Studio 抱怨忽略了
scanf()s 返回值。请教给尽可能多的人。
标签: c