While/Switch 语句奇怪的输出

发布于 2024-12-10 04:56:25 字数 1411 浏览 1 评论 0原文

#include <stdio.h>
#include <iostream>
using namespace std;

float cost, total;
bool loop(char item){
        switch (toupper(item)) {
            case 'A':
                cost = 4.25;        
                return true;
            case 'B':
                cost = 5.57;
                return true;
            case 'C':
                cost = 5.25;
                return true;
            case 'D':
                cost = 3.75;
                return true;
            case 'T':
                return false;
        }
        return true;
}

int main(){
        char item;
        do {
            printf("\nEnter Item Ordered [A/B/C/D] or T to calculate total:");
            scanf("%c", &item);
            total = total + cost;
        } while (loop(item)); 
        printf("Total Cost: $%f\n", total);
}

让我输出一下过程:

$ ./Case3.o 

Enter Item Ordered [A/B/C/D] or T to calculate total:a

Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:b

Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:a

Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:t
Total Cost: $28.139999

为什么在第一个 printf 之后,它打印了两次 printf,但第一次却跳过了我的输入。那么它是如何计算 5.24+5.57+5.24 等于 28.14 的呢?

#include <stdio.h>
#include <iostream>
using namespace std;

float cost, total;
bool loop(char item){
        switch (toupper(item)) {
            case 'A':
                cost = 4.25;        
                return true;
            case 'B':
                cost = 5.57;
                return true;
            case 'C':
                cost = 5.25;
                return true;
            case 'D':
                cost = 3.75;
                return true;
            case 'T':
                return false;
        }
        return true;
}

int main(){
        char item;
        do {
            printf("\nEnter Item Ordered [A/B/C/D] or T to calculate total:");
            scanf("%c", &item);
            total = total + cost;
        } while (loop(item)); 
        printf("Total Cost: $%f\n", total);
}

Let me output the process:

$ ./Case3.o 

Enter Item Ordered [A/B/C/D] or T to calculate total:a

Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:b

Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:a

Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:t
Total Cost: $28.139999

Why is it after the first printf its printing the printf twice but skipping me from input the first time. then how is it calculating 5.24+5.57+5.24 to equal 28.14?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

野稚 2024-12-17 04:56:25

enter 是一个按键 - 你需要考虑它:)

至于你的数学,你永远不会将 total 初始化为 0 因此初始值不确定。

没有注意范围 - 数学的真正答案是,当按下 enter 时,循环会重新添加之前的成本。 Mysticial 的回答中指出了这一点。

enter is a keystroke - you need to account for it :)

As for your math, you never initialize total to 0 therefore the initial value is indeterminate.

Wasn't paying attention to the scoping - the real answer for the math is that the loop re-adds the previous cost when enter is pressed. This is noted in Mysticial's answer.

少跟Wǒ拽 2024-12-17 04:56:25

正如其他人提到的,当您按 Enter 时,会输入两个字符,您输入的字符 + 换行符,您需要考虑这两个字符。

可能的解决方案是:

方法 1:C 方式

 scanf(" %c", &item);
       ^^^

在此处添加一个空格,或者更好的方法,

方法 2:C++ 方式

只需使用 C++ 方式从用户获取输入。

cin >> item;

为什么结果未定义?
因为您没有初始化变量total,这会导致未定义行为给您带来意外的输出。
total 是一个全局变量,因此它将默认初始化为 0.0。
未定义结果的真正原因在@Mystical 的答案中。

As others have mentioned, When you press Enter, two characters get inputted, the character you enter + the newline, You need to account for both of these.

Possible solutions are:

Approach 1: The C way

 scanf(" %c", &item);
       ^^^

Add a space here, or the better approach,

Approach 2: The C++ way

simply use the C++ way of getting input from user.

cin >> item;

Why the result is Undefined?
Because you did not initialize the variable total, This results in Undefined Behavior giving you unexpected output.
total is a global so it will be Default Initialized to 0.0.
Real reason for Undefined result is in @Mystical's answer.

傲性难收 2024-12-17 04:56:25

既然已经提到了换行符,我将回答为什么是28.14的另一个问题。

请注意,在您的 switch 中,默认值只是 return。 cost 永远不会被设置。因此,当它读入换行符时,它会跳过 switch 块并保持成本不变。

结果是这样的:

total = 0;  // It's actually undefined since you didn't initialize, but it probably started as zero.

total += 4.25;    //  For a
total += 4.25;    //  For '\n' after the 'a'

total += 5.57;    //  For b
total += 5.57;    //  For '\n' after the 'b'

total += 4.25;    //  For a
total += 4.25;    //  For '\n' after the 'a'

最终答案:28.14

最后输入的 t 不会添加到 total 中。

Since the newline has been mentioned, I'll answer the other question of why 28.14.

Notice that in your switch, the default is just return. cost is never set. Therefore, when it reads in the newline it skips the switch block and leaves cost untouched.

So the result is this:

total = 0;  // It's actually undefined since you didn't initialize, but it probably started as zero.

total += 4.25;    //  For a
total += 4.25;    //  For '\n' after the 'a'

total += 5.57;    //  For b
total += 5.57;    //  For '\n' after the 'b'

total += 4.25;    //  For a
total += 4.25;    //  For '\n' after the 'a'

Final answer: 28.14

The t that is entered last doesn't get added to total.

撩发小公举 2024-12-17 04:56:25

这很容易解释。当您输入 a 并按 ENTER 键时,这会在输入缓冲区中放置两个 个字符,即 a换行符 字符。

这就是为什么除了第一个之外的所有情况,您都会收到一个虚假的提示,因为它会打印它,然后从标准输入获取换行符。

scanf 实际上是 C++ 中的 C 兼容性问题,您应该使用 cin >>>用于 C++ 样式输入的某些(或者任何与流相关的内容)。

这种字符的双重命中也解释了错误的总数,因为当您得到换行符时,您再次添加当前的成本值在你的主循环中。

由于无论输入的值如何,您都会添加成本,因此您的总计由每个值的两个组成。

输入 a,b,a 后,结果为 4.25 + 5.57 + 4.25 = 14.07 - a4.25代码>,而不是5.2428.14 正好是 14.07 的两倍。

This is easily explained. When you enter a and hit the ENTER key, this places two characters in the input buffer, the a and the newline character.

That's why, for all but the first, you have a spurious prompt since it prints it and then gets the newline from standard input.

scanf is really a C compatibility thing in C++, you should be using cin >> something (or any of the streams-related stuff really) for C++-style input.

This double hit of charcaters also explains the errant total as well since, when you get that newline in, you add the current value of cost again in your main loop.

Your total is composed of two of each value due to the fact that you're adding cost regardless of the value entered.

With your entry of a,b,a, that would be 4.25 + 5.57 + 4.25 = 14.07 - a is 4.25, not 5.24. And 28.14 is exactly twice 14.07.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文