Question:
C++ Question on decimal output?
Casey H.
2010-11-05 22:23:09 UTC
how do I get the output of my C++ program to display as a decimal instead of a whole number? I want it to output 6.15 and it outputs 6.
Six answers:
Unca Alby
2010-11-05 22:33:47 UTC
First of all, how do you have the number defined?



If it's defined as "integer", then you're going to get "6" no matter what.



Secondly, how do you arrive at "6.15"? If, for example, you dividing two integers, say, 615 / 100, then you are performing integer arithmetic on integers. Your result will be an integer.



The solution in the first case is to define the number as "float" or "double" instead of "integer."



The solution in the second case is to make sure you have some floating point numbers in the expression in order to force it to use floating point arithmetic. For example, add a ".0" to at least one of the numbers, say, 615 / 100.0.
laura
2010-11-05 23:35:11 UTC
The first answer is correct. If you're dividing two int numbers, the compiler will chop it off at the decimal, no matter what, with no rounding either. To fix this either initially declare one (or both) of them as float, or you can do it in the equation. In the equation would make more sense if you're not using a variable. Examples:



float x, y;

total=x/y;



int x;

total=x/3.0;

//The 3.0 changes it to float and your answer will be also. Similarly, you could do total=x/float(3); and you'd get the same answer



If you want to have more control over your answer, use the following, located in the library

cout << setprecision(x) << fixed << showpoint;



setprecision will display x number of numbers after the decimal point

fixed displays in decimal form and not scientific

showpoint fills in any empty spaces with zeros (ex: 4/4=1.00)
fulce
2016-12-04 05:33:04 UTC
they're ultimate to point out that once you divide an integer by way of an integer the output is TRUNCATED to an integer. you additionally can lookup the header record iomanip which permits you to the two set the form of decimal places on your output and enforce that they are going to seem whilst the quantity is an entire quantity. yet in the beginning in C/C++ once you divide an integer by way of an integer you get an integer. No ifs ands or buts. So divide it by way of a flow or double.
2010-11-06 04:07:12 UTC
Instead of using int, use double in declaring. For example, instead of int a; use double a; (a is used a name of the variable)
opso
2010-11-05 22:36:58 UTC
int x = 61;

int y = 10;

int z;

z = x/y;

z is going to be equal to 6



double x = 61;

double y = 10;

double z;

z = x/y;

z is going to be equal to 6.1
matt
2010-11-05 23:22:40 UTC
%.1f


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...