2010-03-19 34 views
1

我需要打印兼作以下規則:如何實現以下C++輸出格式?

1) No scietific notation 
2) Maximum decimal point is 3 
3) No trailing 0. 

例如:

0.01  formated to "0.01" 
2.123411 formatted to "2.123" 
2.11  formatted to "2.11" 
2.1   formatted to "2.1" 
0   formatted to "0" 

通過使用.precision(3)和std ::固定的,我只能實現規則1)和規則2),但不排除3)

0.01  formated to "0.010" 
2.123411 formatted to "2.123" 
2.11  formatted to "2.110" 
2.1   formatted to "2.100" 
0   formatted to "0" 

代碼示例波紋管:

#include <iostream> 

int main() { 
    std::cout.precision(3); 
    std::cout << std::fixed << 0.01 << std::endl; 
    std::cout << std::fixed << 2.123411 << std::endl; 
    std::cout << std::fixed << 2.11 << std::endl; 
    std::cout << std::fixed << 2.1 << std::endl; 
    std::cout << std::fixed << 0 << std::endl; 
    getchar(); 
} 

有什麼想法嗎?

+0

的三個規則的組合? – dirkgently 2010-03-19 07:37:20

回答

2

你不能用iostream庫的內置格式來做到這一點。

此外,您不需要在每個輸出上應用固定,因爲它未被重置。

您可以編寫自己的手做:

struct MyFormatter { 
    int precision; 
    double value; 
    MyFormatter(int precision, double value) : precision(precision), value(value) {} 
    friend std::ostream& operator<<(std::ostream& s, MyFormatter const& v) { 
    std::stringstream ss; 
    ss << std::set_precision(v.precision) << std::fixed << v.value; 
    std::string str; 
    ss.str().swap(str); 
    str.resize(str.find_last_not_of("0") + 1); 
    if (str[str.length() - 1] == '.') str.resize(str.length() - 1); 
    s << str; 
    return s; 
    } 
}; 

struct MyFormat { 
    int precision; 
    MyFormat(int precision) : precision(precision) {} 
    MyFormatter operator()(double value) const { 
    return MyFormatter(precision, value); 
    } 
}; 

int main() { 
    MyFormat f(3); 
    std::cout << f(0) << ' ' << f(0.1) << ' ' << f(0.12345) << '\n'; 
    return 0; 
} 
1

對於#3,你需要編寫自己的操縱器去除尾隨零。這沒有內置的操縱器。