我正在尝试用 C++ 编写一个简单的程序,该程序获取购买商品的价格和数量,将其存储在数组中,然后以表格格式输出每件商品的总计。然而,当我将代码中的数字相乘时,我得到了完全奇怪的答案!有人可以告诉我发生了什么事吗?
代码:
#include <iostream>
using namespace std;
int main(int argc, _TCHAR* argv[]) {
float price[4], tot[4];
int amt[4];
cout << "Please enter the price and amount of 4 items:\n";
for (int i = 0; i<4; i++) {
cout << "Price of item " << i + 1 << ": ";
cin >> price[i];
cout << "Amount of item " << i + 1 << ": ";
cin >> amt[i];
if (price[i] <= 0 || amt[i] <= 0) {
cout << "Invalid Input Entry!\n";
break;
}
tot[i] = price[i] * amt[i]; // I can't really see how I could have messed this up...
}
cout << "Total\t\tPrice\t\tAmount\n";
cout << "-----\t\t-----\t\t------\n";
for (int i = 0; i < 4; i++) {
cout << "$" << fixed << cout.precision(2) << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl;
}
system("pause");
return 0;
}
输出:
最佳答案
问题是你输出的是 cout.precision(2)
的返回值(它返回之前的精度,在本例中,最初是 6
,然后是 2
)在每个总价之前。
您需要:
不传递
cout.precision()
的返回值至operator<<
:cout << "$" << fixed; cout.precision(2); cout << tot[i] << ...
或者,调用
precision()
在进入循环之前执行一次:cout.precision(2); for (int i = 0; i < 4; i++) { cout << "$" << fixed << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl; }
使用
std::setprecision()
流操纵器而不是调用cout.precision()
直接:#include <iomanip> for (int i = 0; i < 4; i++) { cout << "$" << fixed << setprecision(2) << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl; }
或
#include <iomanip> cout << setprecision(2); for (int i = 0; i < 4; i++) { cout << "$" << fixed << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl; }
附带说明一下,您不应该使用 \t
字符来控制表格的格式。使用像 std::setw()
这样的流操纵器, std::left
, 等等:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
const int maxItems = 4;
string moneyStr(float amount)
{
ostringstream oss;
// in C++11 and later, you can replace this with std::put_money() instead:
// http://en.cppreference.com/w/cpp/io/manip/put_money
//
// oss << showbase << put_money(amount);
oss << "$" << fixed << setprecision(2) << amount;
return oss.str();
}
int main(int argc, _TCHAR* argv[])
{
float price[maxItems], tot[maxItems];
int amt[maxItems];
int cnt = 0;
cout << "Please enter the price and amount of " << maxItems << " items:" << endl;
for (int i = 0; i < maxItems; ++i)
{
cout << "Price of item " << i + 1 << ": ";
cin >> price[i];
cout << "Amount of item " << i + 1 << ": ";
cin >> amt[i];
if (price[i] <= 0 || amt[i] <= 0) {
cout << "Invalid Input Entry!" << endl;
break;
}
tot[i] = price[i] * amt[i];
++cnt;
}
cout << left << setfill(' ');
cout << setw(16) << "Total" << setw(16) << "Price" << setw(16) << "Amount" << endl;
cout << setw(16) << "-----" << setw(16) << "-----" << setw(16) << "------" << endl;
for (int i = 0; i < cnt; i++) {
cout << setw(16) << moneyStr(tot[i]) << setw(16) << moneyStr(price[i]) << setw(16) << amt[i] << endl;
}
system("pause");
return 0;
}
关于c++ - 数组中的元素相乘在 C++ 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50031644/