Thursday, July 9, 2009

C++ help!!!?

How do i make a floating point number display up to 2 decimal places?


for instance, a program displaying CalBurnedPerStep as a floating point number:


1 calorie should be displayed as 1.00 calorie





and a number like 1.2 should be 1.20


and a number 1.25 will remain same.





here's a snippet of the code:


%26lt;%26lt; setprecision(2) %26lt;%26lt; caloriesBurnedPerStep %26lt;%26lt;


what do i need to insert other than setprecision(n)? It simply doesn't show up the extra 0's that i need it to display.


thanks in advance!

C++ help!!!?
That's easy. You also need to use the 'fixed' notation, as follows:





cout %26lt;%26lt; fixed %26lt;%26lt; setprecision(2) %26lt;%26lt; caloriesBurnedPerStep;
Reply:im sorry...wat?
Reply:if u r using a 'c' programming language den u can simply write "0.2%f" but since u r using c++ it doesnot hold any method directly but u can print it separatedly n den mix.........


like


%26lt;%26lt;22%26lt;%26lt;".00"





hope so u hv understand...............
Reply:im giving you the program? see huv it works


It's Turbo c++





# include%26lt;iostream.h%26gt;


# include%26lt;conio.h%26gt;


# include%26lt;iomanip.h%26gt;


void main()


{


float cal=1.2366475;


cout.setf(floatfield,fixedpoint);


cout.setprecision(2);


cout%26lt;%26lt;cal;


}





Ans:





1.24
Reply:Trying setting CalBurnedPerStep to 0.00 when declaring it.





CalBurnedPerStep = 0.00
Reply:ok whoever that can answer that is SMART!
Reply:yeah i was flipping through my book but low got it first =p


The correct way is to use fixed with setprecision(2). Don't forget the iomanip header file too of course.


No comments:

Post a Comment