【问题标题】:Removing trailing zeros - c++ [duplicate]删除尾随零 - C++ [重复]
【发布时间】:2020-09-11 17:16:29
【问题描述】:

这段代码:

cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;

有了这个输出: 0.002000

但是,我想删除尾随的额外零,但它应该在一行代码中,因为我有很多行像上面那样。

【问题讨论】:

  • 任何有用的 cmets ~ 非常感谢!

标签: c++ trailing


【解决方案1】:

试试这个片段:

cout << "test zeros" << endl;
double x = 200;

cout << "before" << endl;
cout<< std::to_string(x) + "m ----> " + std::to_string(x *0.001)+ "km"<<endl;    


std::string str = std::to_string(x * 0.001);
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );

cout << "after" << endl;
cout<< std::to_string(x) + "m ----> " + str + "km"<<endl;

输出:

test zeros
before
200.000000m ----> 0.200000km
after
200.000000m ----> 0.2km

这比std::setprecision 更好,因为您无需决定要保留多少个 num,而是让实现为您找到它。

这里是documentation 以获取更多信息。

【讨论】:

    【解决方案2】:

    尝试使用std::setprecsion()

    设置小数精度

    设置用于在输出操作中格式化浮点值的小数精度。

    所以在你的情况下,你可以使用:

    std::cout << std::setprecision(3) 
    

    这将删除从 0.0020000 到 0.002 的尾随零

    编辑

    当您想在代码中使用 to_string 时,以下代码可以工作:

    #include <iostream>
    using namespace std;
    int main(){
          int x=1;
          string str2 = to_string(x *0.001);
          str2.erase ( str2.find_last_not_of('0') + 1, std::string::npos );;
          std::cout<<to_string(x)+ "m ----> " + str2+  "km";
    }
    

    【讨论】:

    • 这与问题无关。零来自to_string,而不是std::cout
    • cout " + to_string(x *0.001)+ "km"
    • @3.00AMCoder 看来您根本不需要在代码中使用to_string。如重复问题中所述,您无法阻止 to_string 添加尾随零。如果您使用cout &lt;&lt; x &lt;&lt; "m ----&gt; " &lt;&lt; x * 0.001 &lt;&lt; "km" &lt;&lt; endl,尽管您可以使用setprecision 之类的东西来控制格式。
    • @BessieTheCow yepppp 谢谢,工作完美!
    • 好吧,编辑我的答案,他们下面的代码工作:#include using namespace std; int main(){ int x=1; std::string str1 = std::to_string (x);字符串 str2 = to_string(x *0.001); str1.erase ( str1.find_last_not_of('0') + 1, std::string::npos ); str2.erase ( str2.find_last_not_of('0') + 1, std::string::npos ); std::cout " + str2+ "km"; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2017-09-19
    相关资源
    最近更新 更多