how to use float in C++?

hello guys...i just wanna ask u somethin' about float in C++

this is my program:
#include <iostream>
#include <conio.h>

using namespace std;

int main (){

float bag, weight, price, totalPriceWithTax, totalPrice;

cout<<"Number of bags sold: ";
cin>>bag;
cout<<"Weight per bag: ";
cin>>weight;

cout<<"Price per pound: $5.99";
cout<<"\nSales tax: 7.25%";

totalPrice = price * bag * 5.99f;
totalPriceWithTax = (totalPrice + totalPrice) * 0.0725f;

cout<<"\nTotal price: "<<totalPriceWithTax;

getch ();
return 0;

}



the output:

Number of bags sold: 5
Weight per bag: 5 lb
Price per pound: $5.99
Sales tax: 7.25%

Total price: 7.84727e-044



the total price must be $ 1027.884 instead of 7.84727e-044....can u guys help me for this??
Last edited on
you didn't initialized price, hence you get invalid values.
Additionally, you should always use double or long double because it is more precise than float.

And, when dealing with money, always use integral whole number types (for instance you can just store the number of pennies total or dollars + pennies) because floating point types are inaccurate and will cause mistakes when calculating things with money, even with the precision of long double.
Last edited on
Topic archived. No new replies allowed.