c++如何保留小数点后一位

2024-08-01 0 41

直接方法有四种:使用 std::fixed 和 std::setprecision 函数。使用 std::to_string。使用 std::round。使用 printf。

c++如何保留小数点后一位

如何保留 C++ 小数点后一位

直接方法: 使用 std::fixed 和 std::setprecision 函数。

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double num = 123.456;

    // 保留小数点后一位
    cout <p><strong>使用 std::to_string:</strong></p>
<pre class="brush:php;toolbar:false">#include <iostream>
#include <sstream>

using namespace std;

int main() {
    double num = 123.456;
    stringstream ss;

    // 保留小数点后一位
    ss <p><strong>使用 std::round:</strong></p>
<pre class="brush:php;toolbar:false">#include <iostream>
#include <cmath>

using namespace std;

int main() {
    double num = 123.456;

    // 四舍五入到小数点后一位
    num = round(num * 10) / 10;

    cout <p><strong>使用 printf:</strong></p>
<pre class="brush:php;toolbar:false">#include <iostream>
#include <cstdio>

using namespace std;

int main() {
    double num = 123.456;

    // 保留小数点后一位
    printf("%.1fn", num);  // 输出: 123.5
}</cstdio></iostream>

登录后复制

以上就是c++++如何保留小数点后一位的详细内容,更多请关注叮当号网其它相关文章!

相关文章

猜你喜欢