Use of double in codeblocks gives me int output - c++

#include <iostream> using namespace std;
int main()
{
double x=5.0,y=4.0,z;
z=x+y;
cout<<x<<endl<<y<<endl<<z;
return 0;
}
The above program gives me the following output:
5
4
9
When I have declared the variables to be double and even z as double why do I get the output as integer value(9)??

cout is being helpful here: if the double value is a whole number, then it, by default, does not display a decimal separator followed by an arbitrary number of zeros.
If you want to display as many numbers as the precision that your particular double on your platform has, then use something on the lines of
cout.precision(std::numeric_limits<double>::max_digits10);
cout << fixed << x << endl;

Floating point numbers with no digits after the floating point are printed as integers by default.
To always show the floating point, use setiosflags(ios::showpoint).
You can combine that with fixed and setprecision(n) I/O flags to limit how many digits to print after the floating point. For example:
double d = 5.0;
cout << setiosflags(ios::showpoint) << d << endl; // prints 5.00000
cout << setiosflags(ios::showpoint) << fixed << setprecision(1)
<< d << endl; // prints 5.0

Related

C++ numbers aren't rounding correctly

I am new to Stack Overflow, and programming in general. I am in a few classes for programming C++ and have come across an assignment I am having a bit of trouble with. This program is supposed to take fahrenheit and convert it to celsius. I have seen other programs, but could not find a duplicate to my particular problem. This is my code.
#include <iostream>
using namespace std;
int main()
{
int fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
int celsius = 5.0 / 9 * (fahrenheit - 32.0);
cout << "Celsius: " << celsius << endl;
return 0;
}
So this is working great on 4 of the 5 tests that are run. It rounds 22.22 to 22 and 4.44 to 4 like it should, but when 0 F is put in, it rounds -17.77 to -17 instead of -18. I have been researching for about an hour and would love some help! Thank you.
Use std::round() instead of relying on the implicit conversion from double to int. Either that, or do not use conversion at all, show the temperature as a double.
EDIT: As others already pointed out, implicit conversion will not round but truncate the number instead (simply cut off everything after the decimal point).
Integers round down implicitly, as do casts to integer types.
Most likely, using a float in place of an int would give the most sane results:
#include <iostream>
using namespace std;
int main()
{
int fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
float celsius = 5.0 / 9 * (fahrenheit - 32.0);
cout << "Celsius: " << celsius << endl;
return 0;
}
To get normal-looking output (fixed-point like "14.25", not scientific with e notation), pass std::fixed to cout before printing the floating point. You can also use cout.precision() to set the number of digits you would like in the output.
If for some other reason you need an int, use std::round() around the right hand of the expression.
When the compiler converts a floating point number to an integer, it doesn't round, it truncates. I.e. it simply cuts of the digits after the decimal point. So your program behaves as it is programmed to do.
int x = 3.99;
int y = std::round(3.99);
std::cout
<< "x = " << x << std::endl
<< "y = " << y << std::endl
;
-->
x = 3
y = 4
C/C++ is not doing floating point round when static_cast<int>-ing a float to an int. If you want to round, you need to call library function std::round()

How to cout a float/double with dynamic precision? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 3.14159;
double b = 3.14159;
cout.precision(6);
cout << a << endl; //3.14159
cout << b << endl; //3.14159
cout.precision(10);
cout << a << endl; //3.141590118
cout << b << endl; //3.14159
cout.precision(20);
cout << a << endl; //3.141590118408203125
cout << b << endl; //3.1415899999999998826
return 0;
}
Can anyone explain the difference between float and double?
How do we print float/double with dynamic precision?
Assuming I have your definition of dynamic correct something like this should work:
void print(float toPrint, int precision)
{
cout.precision(precision);
cout << toPrint <<endl;
}
cout.precision only changes the precision of the printing, it doesn't actually affect how precise the numbers are. If you print with more digits than your numbers have precision, you will get inaccurate digits.
Of course, cout.precision also only changes the maximum precision of the printing. To force it to print trailing zeros, do something like this:
void print(float toPrint, int precision)
{
cout.precision(precision);
cout << fixed;
cout << toPrint <<endl;
}
The difference between a float and a double is that a double is approximately twice as precise as a float. In general, a float has something like 7 or 8 digits of precision, and a double has 15 or 16 digits of precision.
If I'm reading your question correctly you are wondering why both floats and doubles lose precision after you adjust cout.precision.
This occurs because floating point numbers are stored in binary differently than normal whole numbers. A common example of why this matters is that the number 0.6 is stored in binary as 0011111100101.... This, like 0.6666666... in decimal, is an infinitely long number. Thus, your computer needs to decide at what point it should round/approximate the value. When you declare and initialize your floating point numbers a and b, the computer knows that it does not need to cram any value other than 3.14159 into the variable. However, when you then change cout.precision, the computer thinks it needs to round the floating point at a later location. Furthermore, floats are only 16 bits so it will almost always be less precise than the double, which is 32 bits. See here for their ranges.
Obviously to get the correct precision you shouldn't adjust cout.precision to be greater than the number of digits of your variable. However if you want to adjust the precision and just print out a bunch of zeroes after the end of your initial variable value, just use cout << fixed << setprecision(number). See below:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 3.14159;
double b = 3.14159;
cout.precision(6);
cout << a << endl; //3.14159
cout << b << endl; //3.14159
cout << fixed << setprecision(10);
cout << a << endl; //3.141590118
cout << b << endl; //3.141590000
return 0;
}
Edit: Another option is to use limits.
It doesn't make sense to have a "dynamic precision" where all digits different from 0 are displayed. That mode would have issues with fractional numbers that have infinite decimal digits, like the result of 1.0 / 3.
The best you can do is to set the maximum precision you are willing to see with precision, just like in your example.

How to express large numbers to two decimal places in C++ Calculator

I am trying to write a calculator in C++ that does the basic functions of /, *, -, or + and shows the answer to two decimal places (with 0.01 precision).
For example 100.1 * 100.1 should print the result as 10020.01 but instead I get -4e-171. From my understanding this is from overflow, but that's why I chose long double in the first place!
#include <iostream>
#include <iomanip>
using namespace std;
long double getUserInput()
{
cout << "Please enter a number: \n";
long double x;
cin >> x;
return x;
}
char getMathematicalOperation()
{
cout << "Please enter which operator you want "
"(add +, subtract -, multiply *, or divide /): \n";
char o;
cin >> o;
return o;
}
long double calculateResult(long double nX, char o, long double nY)
{
// note: we use the == operator to compare two values to see if they are equal
// we need to use if statements here because there's no direct way
// to convert chOperation into the appropriate operator
if (o == '+') // if user chose addition
return nX + nY; // execute this line
if (o == '-') // if user chose subtraction
return nX - nY; // execute this line
if (o == '*') // if user chose multiplication
return nX * nY; // execute this line
if (o == '/') // if user chose division
return nX / nY; // execute this line
return -1; // default "error" value in case user passed in an invalid chOperation
}
void printResult(long double x)
{
cout << "The answer is: " << setprecision(0.01) << x << "\n";
}
long double calc()
{
// Get first number from user
long double nInput1 = getUserInput();
// Get mathematical operations from user
char o = getMathematicalOperation();
// Get second number from user
long double nInput2 = getUserInput();
// Calculate result and store in temporary variable (for readability/debug-ability)
long double nResult = calculateResult(nInput1, o, nInput2);
// Print result
printResult(nResult);
return 0;
}
setprecision tells it how many decimal places you want as an int so you're actually setting it to setprecision(0) since 0.01 get truncated. In your case you want it set to 2. You should also use std::fixed or you'll get scientific numbers.
void printResult(long double x)
{
cout << "The answer is: " << std::fixed << setprecision(2) << x << "\n";
}
working example
It is not due to overflow you get the strange result. Doubles can easily hold numbers in the range you are showing.
Try to print the result without setprecision.
EDIT:
After trying
long double x = 100.1;
cout << x << endl;
I see that it doesn't work on my Windows system.
So I searched a little and found:
print long double on windows
maybe that is the explanation.
So I tried
long double x = 100.1;
cout << (double)x << endl;
which worked fine.
2nd EDIT:
Also see this link provided by Raphael
http://oldwiki.mingw.org/index.php/long%20double
The default floating point presentation switches automatically between presentation like 314.15 and 3.1e2, depending on the size of the number and the maximum number of digits it can use. With this presentation the precision is the maximum number of digits. By default it's 6.
You can either increase the maximum number of digits so that your result can be presented like 314.15, or you can force such fixed point notation by using the std::fixed manipulator. With std::fixed the precision is the number of decimals.
However, with std::fixed very large and very small numbers may be pretty unreadable.
The setprecision() manipulator specifies the number of digits after the decimal point. So, if you want 100.01 to be printed, use setprecision(2).
When you use setprecision(0.01), the value 0.01 is being converted to int, which will have a value of 0.
It wouldn't have hurt if you had actually read the documentation for setprecision() - that clearly specifies an int argument, not a floating point one.

Why does cout truncate a double?

The following is my console input/output.
Please enter a real number: -23486.33
Characters checked: 9
Thank you.
The real number you entered is -23486.3
The value I entered is -23486.33, but yet cout prints it as -23486.3.
The relevant code is below:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Function prototype (declaration)
string readDouble();
bool isValidDouble(string);
int main()
{
string value;
double number;
value = readDouble();
while (!isValidDouble(value)) {
cout << "The number you entered is not a valid integer." << endl;
value = readDouble();
}
number = atof(value.c_str());
cout << "Thank you." << endl
<< "The real number you entered is " << number << endl;
}
When debugging, I check the value of number right after the method call atof(value.c_str())l;. Number is shown to have a value of -23486.33. So what happens between that and the print out by cout? In no part of my code do I set the precision of cout or make it fixed.
If you have any questions, please let me know.
Have you tried
std::cout << std::setprecision(2) << number;
look at:
http://www.cplusplus.com/reference/iomanip/setprecision/
-23486.3 is displayed because std::cout prints only 6 digits by default.
To print back a number entered from standard input (convertion text → floating number → text), you can use set_precision with digits10 as precision:
double d = -23486.33;
int precision = std::numeric_limits<double>::digits10;
std::cout << std::setprecision(precision) << d << std::endl;
This displays:
-23486.33
To print a number with full precision (usually for convertion floating number → text → floating number), you can use set_precision with max_digits10 as precision:
double d = -23486.33;
int precision = std::numeric_limits<double>::max_digits10;
std::cout << std::setprecision(precision) << d << std::endl;
This displays:
-23486.330000000002
Here the printed number is not the same because -23486.33 doesn't have an exact representation in IEEE encoding (expressed in base 2 instead of base 10).
For more details with digits10 and max_digits10, you can read:
difference explained by stackoverflow
digits10
max_digits10
Set a precision when you output a double and keep precision explicitly when you compare them.
When you convert a string presentation of a DEC number to a double(float point number presentation), the data in the memory might not be mathematically equal to the string presentation. It's the best approximation by a float point number presentation, and vise versa.
You can set the precision to the maximum limit for double.
The code snippet is here:
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
double number = ... // your double value.
cout << setprecision(numeric_limits<double>::digits10) << number << endl;

print X number after the decimal point using the cout

I have this code:
double a = 7.456789;
cout.unsetf(ios::floatfield);
cout.precision(5);
cout << a;
and also this one:
double a = 798456.6;
cout.unsetf(ios::floatfield);
cout.precision(5);
cout << a;
the result of the first code is: 7.4568
Which is almost what I want (what I want to recieve is 7.4567)
the result of the second : 7.9846e+05
Which is not at all what I want (I want 798456.6)
I want to print the number till 4 numbers after the decimal point
How can I do that ?
By using unsetf(), you are telling cout to use its default formatting for floating-point values. Since you want an exact number of digits after the decimal, you should be using setf(fixed) or std::fixed instead, eg:
double a = ...;
std::cout.setf(std::fixed, ios::floatfield);
std::cout.precision(5);
std::cout << a;
.
double a = ...;
std::cout.precision(5);
std::cout << std::fixed << a;