while / Switch语句输出 [英] While/Switch Statement weird output

查看:320
本文介绍了while / Switch语句输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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?

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?

推荐答案

字符输入,您输入的字符+换行符,您需要考虑这两个。

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.

可能的解决方案是:

方法1:C方式 >

Approach 1: The C way

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

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

Add a space here, or the better approach,

方法2:使用C ++方式

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

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

cin >> item;

为什么结果是未定义?

<由于您未初始化变量 total ,这会导致未定义行为给您意外的输出。

total 是一个全局变量,因此它将 Default Initialized 设置为0.0。

未定义结果的真正原因是@神秘的答案。

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.

这篇关于while / Switch语句输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆