While/Switch语句奇怪的输出
While/Switch Statement weird output
#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
键时,这会在输入缓冲区中放置两个字符,a
和newline
字符。
这就是为什么,除了第一个,您有一个虚假的提示,因为它打印它,然后从标准输入获得newline
。
scanf
在c++中确实是C兼容的东西,你应该使用cin >> something
(或者任何与流相关的东西)作为c++风格的输入。
字符的双重命中也解释了错误的总数,因为当获得 newline
时,您在主循环中再次添加cost 的当前值。
由于无论输入的值是多少,都在添加cost
,因此您的总数由每个值的两个组成。
输入a,b,a
,即4.25 + 5.57 + 4.25 = 14.07
- a
是4.25
,而不是5.24
。28.14
正好是14.07
的两倍
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- if/else 语句输出由于加号或减号而未显示正确的消息
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 为什么当 while 循环中的 if 条件变为 false 时,我的函数不输出最后一条语句?
- C++:更改 IF 语句中的输出文件
- c++:if 语句无法正常运行,并继续执行无效输出
- C++如果使用 lambda 表达式的语句返回 true,但输出来自 false,为什么
- 输出错误命令的条件语句
- 为什么我得到错误的输出 - If & Else 语句
- C# 读取完全锁定的文本文件或读取 if 语句外部的输出
- 如果/else语句未显示/可变分配问题的输出;初学者程序员
- 从类模块检索信息以在 switch 语句中输出时出现问题
- 切换语句在 C++ 中的输出不清楚
- Cpp 切换语句不会输出条件集
- Switch语句不显示除默认语句之外的任何类型的输出
- 删除"超出矢量误差范围"的打印语句后输出不同的根本原因
- cout 输出乱码消息行,而不是实际用户的 cout 语句
- 最后一行欧普特两个组合输出问题?如果其他语句
- 添加 cout 语句会更正输出
- c++中while循环执行中的打印输出语句