While/Switch语句奇怪的输出

While/Switch Statement weird output

本文关键字:输出 语句 Switch While      更新时间:2023-10-16
#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: $%fn", 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,但第一次从输入中跳过了我。那么它怎么计算5.24+5.57+5.24等于28.14呢?

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

至于你的数学,你从来没有将total初始化为0,因此初始值是不确定的。

没有注意作用域——数学的真正答案是,当enter被按下时,循环重新添加了之前的代价。

正如其他人提到的,当您按Enter键时,输入两个字符,the character you enter + the newline,您需要考虑这两个字符。

可能的解决方案如下:

方法1:C方式

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

在这里添加一个空格,或者更好的方法,

方法2:c++方法

简单地使用c++方式从user获取输入。

cin >> item;

为什么结果是Undefined?

由于没有初始化变量total,这将导致未定义行为给您意想不到的输出。total是一个全局变量,所以它将Default Initialized设置为0.0。未定义结果的真正原因在@ mystic的答案中。

既然已经提到了newline,那么我将回答另一个问题:为什么是28.14

请注意,在您的开关中,默认值只是return。cost从未设置。因此,当它读入newline时,它跳过switch块,使cost保持不变。

所以结果是:

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

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

这就是为什么,除了第一个,您有一个虚假的提示,因为它打印它,然后从标准输入获得newline

scanf在c++中确实是C兼容的东西,你应该使用cin >> something(或者任何与流相关的东西)作为c++风格的输入。

字符的双重命中也解释了错误的总数,因为当获得 newline时,您在主循环中再次添加cost 的当前值

由于无论输入的值是多少,都在添加cost,因此您的总数由每个值的两个组成。

输入a,b,a,即4.25 + 5.57 + 4.25 = 14.07 - a4.25,而不是5.2428.14正好是14.07的两倍