cout으로 올바른 소수점 이하 자릿수 인쇄


133

float값 목록이 있고 cout소수점 이하 두 자리 로 인쇄하고 싶습니다 .

예를 들면 다음과 같습니다.

10.900  should be printed as 10.90
1.000 should be printed as 1.00
122.345 should be printed as 122.34

어떻게해야합니까?

( setprecision이것에 도움이되지 않는 것 같습니다.)

답변:


196

로에게 <iomanip>, 당신이 사용할 수있는 std::fixedstd::setprecision

여기에 예가 있습니다

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

그리고 당신은 출력을 얻을 것이다

122.34

6
왜 프로그램에서 "std : fixed"를 사용 했습니까?
Vilas Joshi 2016 년

1
이를 위해 유용한 헤더를 정의 할 수 있습니다 #define FIXED_FLOAT(x) std::fixed <<std::setprecision(2)<<(x) . 사용법은 다음과 같습니다.cout<<FIXED_FLOAT(d)
Udayraj Deshmukh

13
@VilasJoshi, setprecision은 소수점 이하 자릿수를 설정합니다 .5 자리가 있고 setprecision (2)을 사용하면 2 자리가되지만 0 자리가 없으면 아무것도 표시되지 않습니다. 고정을 사용하면 많은 자릿수가 수정됩니다. 5는 5.00 no 5로 표시됩니다.
vaibnak

43

당신은 거의 거기에 있었고 std :: fixed도 사용해야합니다 .http : //www.cplusplus.com/reference/iostream/manipulators/fixed/를 참조하십시오 .

#include <iostream>
#include <iomanip>

int main(int argc, char** argv)
{
    float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };

    std::cout << std::setprecision(2) << std::fixed;

    for(int i = 0; i < 6; ++i)
    {
        std::cout << testme[i] << std::endl;
    }

    return 0;
}

출력 :

0.12
1.23
12.35
123.45
1234.50
12345.00

18

setprecision(n)소수 부분이 아닌 정수에 적용됩니다. 소수 부분에 적용하려면 고정 소수점 형식을 사용해야합니다.setiosflags(ios::fixed)


12

허용 된 답변을 단순화

단순화 된 예 :

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;
    std::cout << std::fixed << std::setprecision(2) << d;
}

그리고 당신은 출력을 얻을 것이다

122.34

참고:


이것은 나를 위해 일했다 : std :: cout << std :: setprecision (2) << std :: fixed << d;
Andrea Girardi

5

일관된 형식을 원하면서 정수에 문제가있었습니다.

완전성을위한 재 작성 :

#include <iostream>
#include <iomanip>

int main()
{
    //    floating point formatting example

    double d = 122.345;
    cout << std::fixed << std::setprecision(2) << d << endl;
    //    Output:  122.34


    //    integer formatting example

    int i = 122;
    cout << std::fixed << std::setprecision(2) << double(i) << endl;
    //    Output:  122.00
}

네임 스페이스를 사용하지 않기 때문에 cout 및 endl 직전에 std ::가 누락되었습니다.
blackforest-tom

@ blackforest-tom-아마도 당신이 옳고, 기억할 수 없습니다 --- 나는 일반적으로 작업 프로그램을 복사하여 붙여 넣습니다. 그래서 이것은 Visual Studio 또는 다른 곳에서 그대로 실행될 수 있습니다.
Manohar Reddy Poreddy

3

코딩 경쟁에서 이와 비슷한 문제가 있었고 이것이 내가 처리 한 방법입니다. 모든 double 값에 정밀도 2를 설정

먼저 setprecision을 사용하기 위해 헤더를 추가하십시오.

#include <iomanip>

그런 다음 메인에 다음 코드를 추가하십시오.

  double answer=5.9999;
  double answer2=5.0000;
  cout<<setprecision(2)<<fixed;
  cout <<answer << endl;
  cout <<answer2 << endl;

산출:

5.99
5.00

5.00을 쓰기 위해 fixed를 사용해야하므로 출력이 5.00이되지 않습니다.

도움이되는 짧은 참조 비디오 링크


2

'float mode'를 fixed로 설정해야합니다.

float num = 15.839;

// this will output 15.84
std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl;

1

소수점 뒤에 고정 된 2 자리를 설정하려면 다음을 먼저 사용하십시오.

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

그런 다음 이중 값을 인쇄하십시오.

이것은 예입니다 :

#include <iostream>
using std::cout;
using std::ios;
using std::endl;

int main(int argc, char *argv[]) {
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    double d = 10.90;
    cout << d << endl;
    return 0;
}

1
#include<stdio.h>
int main()

{

 double d=15.6464545347;

printf("%0.2lf",d);

}

0

템플릿

#include <iostream>

// d = decimal places
template<int d> 
std::ostream& fixed(std::ostream& os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << fixed<2> << d;
}

너비 옵션도 과학적으로 유사합니다 (열에 유용)

// d = decimal places
template<int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

// d = decimal places
template<int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << f<10,2> << d << '\n'
        << e<10,2> << d << '\n';
}

-3

사소한 점; 헤더에 다음을 넣으십시오

네임 스페이스 std 사용;

그때

std :: cout << std :: fixed << std :: setprecision (2) << d;

~로 단순화되다

cout << 고정 << setprecision (2) << d;


2
그렇습니다. "간체 화"되었으나 권장하지 않습니다. using namespace std;그것을 위해 사용하지 마십시오 -왜 그렇게하는지 이해하십시오.
Carlos F

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.