2015-01-17 1 views
1

나는 두루마기 개념을 가진 & 수레에 어려움을 겪고 있습니다. 마지막 줄에서 C++ 플로트 질문

#include <stdio.h> 
#include <iostream> 
#include <iomanip> 
using namespace std; 

int main() { 

    const float classA = 15.00f; 
    const float classB = 12.00f; 
    const float classC = 9.00f; 
    int soldA, 
    soldB, 
    soldC; 
    float total = 1.00f; 

    std::cout << "How many Class A tickets where sold? : "; 
    std::cin >> soldA; 
    std::cout << "How many class B tickets were sold? : "; 
    std::cin >> soldB; 
    std::cout << "How many Class C tickets were sold? : "; 
    std::cin >> soldB; 

    printf("%f\n", total = (classA * soldA) + (classB * soldB) + (classC * soldC)); 

    std::cout <<"The total amount collected : $" << total << endl; 
} 

, 나는 2 (달러 등)의 정밀도 부동 소수점으로 총 인쇄 할,하지만 난 컴파일 할 때의 printf에서 잘 작동하지만 마지막 줄에 정밀도를 잃는다 .

어떻게 수정합니까? 아니면 정밀도를 보여?

+0

[' setprecision'] (http://en.cppreference.com/w/cpp/io/manip/setprecision) – Borgleader

+5

금전적 가치를 수레에 저장하지 마십시오. –

+2

'printf'는 당신이 생각하는대로하지 않습니다 ... 인쇄 만하고 C 레거시 함수이기 때문에 C++에서 사용하지 마십시오. 할당을'total'으로 자체 행으로 옮기고,'printf' 인수에 넣지 마십시오 (C/C++에서는 유효하지만 일반적으로 혼란 스럽습니다. 여기에서는'printf'와 함께 특별한 것을한다고 생각하는 것 같습니다. 하지만 그렇지 않습니다). – hyde

답변

0
#include <stdio.h> 
#include <iostream> 
#include <iomanip> 
using namespace std; 

int main() { 

    const float classA = 15.00f; 
    const float classB = 12.00f; 
    const float classC = 9.00f; 
    int soldA,soldB,soldC; 
    float total = 1.00f; 

    std::cout << "How many Class A tickets where sold? : "; 
    std::cin >> soldA; 
    std::cout << "How many class B tickets were sold? : "; 
    std::cin >> soldB; 
    std::cout << "How many Class C tickets were sold? : "; 
    std::cin >> soldC; 

    printf("%f\n", total = (classA * soldA) + (classB * soldB) + (classC * soldC)); 

    std::cout.precision(2);  // set precision 
    std::cout << std::fixed; // use the precision for numbers like 66.000000 
    std::cout <<"The total amount collected : $" << total << endl; 
} 

이 즐길 수 :)

1

당신은이 같은 std::cout에 정밀도를 설정해야합니다 :

std::cout.precision(2); 
std::cout <<"The total amount collected : $" << total << endl; 

또는 당신은 또한 다음과 같이 설정할 수 있습니다 :

std::cout <<"The total amount collected : $" << std::setprecision(2) << total << endl;