Linux 拨号vps windows公众号手机端

c++保留小数点后几位如何弄

lewis 7年前 (2018-01-22) 阅读数 6 #程序编程
文章标签 c++

在C++中,可以使用以下方法来保留小数点后几位:

  1. 使用fixedsetprecision函数:
#include <iostream>
#include <iomanip>
int main() {
double number = 3.1415926;
int precision = 2;
std::cout << std::fixed << std::setprecision(precision) << number << std::endl;
return 0;
}

输出结果为3.14

  1. 使用字符串流(stringstream):
#include <iostream>
#include <sstream>
#include <iomanip>
int main() {
double number = 3.1415926;
int precision = 2;
std::stringstream ss;
ss << std::fixed << std::setprecision(precision) << number;
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}

输出结果为3.14

  1. 使用printf函数:
#include <iostream>
#include <cstdio>
int main() {
double number = 3.1415926;
int precision = 2;
std::printf("%.2f\n", number);
return 0;
}

输出结果为3.14

以上是三种常用的保留小数点后几位的方法,你可以根据自己的需求选择其中一种方法来使用。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门