I was wondering how can you only print the decimal places of the number?
I need to print 10.30 as 10m,30cm and I have no idea how to do that.
I have tried to google the solution, but didn't find anything helpful.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double P;
cin >> P;
cout << fixed << setprecision(0) << P << "m," << setprecision(2) << P << "cm";
return 0;
}
Given a double P, and assuming you wanted to round half-way any fractions of cm, this is one approach:
unsigned long cm = std::round(P * 100); // ToDo - check the possibility of overflow
std::cout << cm / 100 << "m, " << cm % 100 << "cm";
Where I'm using integer arithmetic to extract the m, and modulo arithmetic to extract the cm. Enhance to handle negative P as required.
Related
my goal is to turn a double's fraction part into an integer, for example: turn 0.854 into 854 or turn 0.9321 into 9321 (the whole part of the double is always 0)
i was doing it like this, but i dont know how to fill the while's parameters to make it stop when variable x becomes a whole number without a fraction:
double x;
cin >> x;
while(WHAT DO I TYPE HERE TO MAKE IT STOP WHEN X BECOMES A WHOLE NUMBER){
x *= 10;
}
it would be best if i could do it with a loop, but if it is not possible, i am open to other suggestions :)
That question has no answer in a mathematical/logical sense. You have to read how floating point numbers in computers work, see e.g.
https://en.wikipedia.org/wiki/Floating-point_arithmetic
and understand that they are not decimal point numbers in memory. A floating point number in memory consists of three actual numbers: significant * base^{exponent} and according to IEEE the base used is "2" in basically any modern floating point data, but in even more generality, the base can be anything. Thus, whatever you have in your mind, or even see on your screen as output, is a misleading representation of the data in memory. Your question is, thus, mainly a misconception of how floating point numbers in computers work...
Thus, what you specifically ask for does in general not exist and cannot be done.
However, there may be special application for output formatting or whatever where something like this may make sense -- but then the specific goal must be clearly stated in the question here. And in some of such cases, using a "string-based" approach, as you suggested, will work. But this is not an answer to your generic question and has the high potential to also mislead others in the future.
Actually, one way to make your question obvious and clear is to also specify a fixed desired precision, thus, numbers after the decimal point. Then the answer is quite trivially and correctly:
long int value = fraction * pow(10, precision);
In this scenario you know 100% what your are doing. And if you really like you could subsequently remove zeros from the right side...
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
However there is another principle problem on a numerical level: there is no mathematical difference between, e.g., 000003 and just 3, thus in any such application the input 0.000003 will give the same results as 0.0003 or 0.3 etc. This cannot be a desired functionality... it is pretty useless to ask about the *value of the fractional part of a floating point number. But, since we have a known precision`, we can do:
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
which will fill in the eventually missing leading zeros.
See this complete tested test code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double v = 0.0454243252;
int precision = 14;
long int value = v*pow(10,precision);
cout << value << endl;
// 4542432520000
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
cout << value << endl;
// 454243252
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
// 0454243252
}
Here is a possible approach:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Enter Number: ";
double user_input;
cin >> user_input;
int user_input_to_int = int(user_input);
double decimal_value = user_input - user_input_to_int;
ostringstream oss;
oss << std::noshowpoint << decimal_value;
string num_str = oss.str();
int str_length = num_str.size()-2;
int multiplier = 1;
for (int x = 0; x < str_length; x++)
{
multiplier *= 10;
}
cout << "\n";
cout << "Whole number: " << user_input_to_int << endl;
cout << "Decimal value: " << decimal_value*multiplier << endl;
}
Compare the difference between double and integer part. It is working only if x is less than 2^63.
while (x - long long(x) > 0)
find 2 real numbers find the fractional part smaller than these numbers
This question already has answers here:
Printing the correct number of decimal points with cout
(13 answers)
Closed 1 year ago.
As a newbie in the world of programming, I have to write a bit of C++ code to find the average of two numbers.
However, my code somehow appears to be incorrect. Please take a look at my code:
#include <iostream>
using namespace std;
int main() {
float a, b, average;
cin >> a;
cin >> b;
average = (a+b)/2;
cout << average << endl;
}
however, it says I am wrong because when I input 10 10 it outputs 10 but the system wants me to output 10.00
You need to use some I/O manipulators.
std::setprecision and std::fixed
Example:
#include <iomanip>
#include <iostream>
int main() {
if(float a, b; std::cin >> a >> b) {
float average = (a+b)/2;
std::cout << std::fixed << std::setprecision(2) << average << '\n';
}
}
Like others have said you need to change your cout line to:
cout << fixed << setprecision(2) << average << endl;
Remember that with the <<s you're putting a stream of data (an iostream) into cout. The first piece of data is std::fixed which says "Display floats to a fixed number of decimal places, don't cut off any trailing zeros." And then std::setprecision(2) says "Make that fixed number of decimal places 2." You could use an int variable or another number in place of 2 if you wanted. From there the stream has your average and an endline like before.
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.
#include <iostream>
using namespace std;
#include <iomanip> // std::setprecision
int main() {
float a, b, average;
cin >> a;
cin >> b;
average = (a+b)/2;
cout << fixed << setprecision(2) << average << endl;
}
#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
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;
well basically if I write something like this -
float a = 0;
a = (float) 1/5;
a += (float) 1/9;
a += (float) 1/100;
It will automatically decrase precision to 2 digits after comma, but I need to have 5 digits after comma, is it available to create, so it displays 5 digits? With setprecision(5) it, just shows 00000 after comma.
It get's all data from input file just fine.
setprecision do not modify value. It's only display desired precision when you using ofstream
You have to use setprecision like this:
cout << setprecision (5) << a << endl;
http://www.cplusplus.com/reference/iostream/manipulators/setprecision/
EDIT: I haven't used C++ in a while but you may be getting some problems because you are doing integer division and then casting the result to a float. Try doing it like this instead to force a float division:
a+=1.0f/100;
this will give 5 digits after comma:
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argi, char** argc) {
float a = 0;
a = (float) 1/5;
a += (float) 1/9;
a += (float) 1/100;
cout << setprecision(5) << a << endl;
return 0;
}
if you want to have always 5 digits on output, maybe use this:
cout << setprecision(5) << setfill ('0')<< setw(5) << a << endl;
You have some reading to do:
http://www.google.com/?q=what+every+programmer+should+know+about+floating+point