【发布时间】:2011-10-18 04:46:49
【问题描述】:
#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?
【问题讨论】:
-
如果是C++,使用
cout将输出写入流,cin接受输入。 -
输入中的换行符是原因。见stackoverflow.com/questions/1247989/…
-
printf 让我觉得很花哨……
-
用
scanf("%c%*c", &item);修复
标签: c++ switch-statement do-while