도서 : 초보자를 위한 C++ 프로그래밍(성안당)

지음 : 강성수 지음


 

 

  • 실수 123.4569를 float과 double로 저장하고 소수점 이하 3자리까지 출력해 보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
 
int main() {
    float a = 123.4569f;
    double b = 123.4569;
 
    cout.setf(ios::fixed, ios::floatfield); //부동소수점 표기
    cout.precision(3); //소수점 이하 3자리, 고정 소수점표기 함께 사용
 
    cout << "float : " << a << endl;
    cout << "double : " << b << endl;
 
    return 0;
}
cs
  • 결과


  • 키보드에서 두 개의 정수와 한 개의 실수를 입력하고 출력되는 간격을 다르게 하여 출력해 보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
#include <iomanip>
 
int main() {
    int a, b;
    float c;
 
    cout << "두 개의 정수와 한 개의 실수를 입력할 겁니다.\n";
    cout << "첫 번째 정수를 입력해 주세요.\n";
    cin >> a;
    cout << "두 번째 정수를 입력해 주세요.\n";
    cin >> b;
    cout << "실수를 입력해 주세요.\n";
    cin >> c;
 
    cout << "각 수들의 글 간격을 다르게 출력해 보겠습니다.\n";
    cout << setw(10<< a << endl;
    cout << setw(20<< b << endl;
    cout << setw(30<< c << endl;
 
    return 0;
}
cs
  • 결과

 

+ Recent posts