[英]Is there a way to format output more specifically in C++?
當我將setprecision()
中的值分配給1
和
{ 1, 1, 1, 2, 1, 1, 1, 4, 1, 0, 1, 1 }
被輸入為值,MyProgrammingLab 說我在 output 中有一個錯誤 for average
。 我的程序應該顯示1.2
時顯示1.25
。
因此,當我將setprecision()
中的值更改為2
和
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }
作為值輸入,MyProgrammingLab 再次說我在 output 中有一個錯誤 for average
。 我的程序應該只顯示6.50
時顯示6.5
。
我該怎么做才能在兩種情況下正確輸出average
?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Creating int variable to hold total
double total = 0;
// Array
double value[12];
// Loop to prompt user for each value
for (int i = 0; i < 12; i++) {
cout << "Enter value: ";
cin >> value[i];
}
// Loop to add all values together
for (int i = 0; i < 12; i++)
total += value[i];
// Creating a double to hold average
double average;
// Formatting output
cout << fixed << showpoint << setprecision(2);
// Calculating average
average = total / 12;
// Displaying average
cout << "Average value: " << average << endl;
return 0;
}
您可以編寫一個小助手 function 以您想要的方式格式化字符串。 我已經在我的代碼中添加了注釋來解釋。
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
std::string RemoveTrailingZero(double value)
{
//Convert to precision of two digits after decimal point
std::ostringstream out;
out << std::fixed << std::setprecision(2) << value;
std::string str = out.str();
//Remove trailing '0'
str.erase(str.find_last_not_of('0') + 1, std::string::npos);
//Remove '.' if no digits after it
if (str.find('.') == str.size() - 1)
{
str.pop_back();
}
return str;
}
int main()
{
std::cout << RemoveTrailingZero(1.25) << std::endl;
std::cout << RemoveTrailingZero(6.50) << std::endl;
std::cout << RemoveTrailingZero(600.0) << std::endl;
}
Output:
1.25
6.5
600
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.