Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to write a program in C++ to cin a Decimal number and cout the digits after Decimal
for example 0.26547 -> 5.
I wrote this but not work correctly:
int main()
{
int i=0,b;
float a ;
cin>>a ;
while(a!=0)
{
a*=10 ;
b=a ;
a-=b ;
i+=1 ;
}
cout<<i ;
}
For example for 0.258 instead of 3, returns 20.
can one explain me what is the problem of this code ?
thank you
C++ permits decimal representation of floating point numbers, but as far as I know all extant implementations use binary representation. And then the idea of storing the user's decimal number specification as a floating point value, loses critical information about the decimal digits: they're simply not there any more. So to count the decimal digits in the specification, you have to store it as a string.
Pseudo-code:
input number specification as a string, e.g. using getline.
verify that it's a valid number specification, e.g. using stod.
scan for the first period from the right, call this position P.
scan for the maximum number of decimal digits from position P.
I am unsure why your code does not work (What compiler are you using?), but I think it might related to
b=a;
Try explicitly casting your float to an int
b = int(a);
Alternatively, you could choose not to use an int, and round a float down using the function floor by including math.h #include <math.h>
float a = 5.9f;
float b = floor(a);
a -= b;
Related
This question already has answers here:
How to 'cout' the correct number of decimal places of a double value?
(9 answers)
Where and How to format a C++ code to 2 decimal places
(1 answer)
Closed 1 year ago.
#include <iostream>
using namespace std;
int main()
{
double d = 4, b, e;
cin >> b;
e = b + d;
cout <<e<< endl;
}
why is my output not coming in double form, when everything I've declared is double?
I've already tried typecasting it, but still, it's not working as I want it to work.
When I give 4.0 as input, it gives 8 as output but I want it to give 8.0 as the output.
There is no double form. Printing necessitate a format, a specification of the way the result is outputted, whatever you print.
ostreams does have an internal states to decide the way a given argument is printed. Basically, these can be controlled through input/output manipulators. There is some that can be applied to control floating-point output.
Non exhaustive list:
std::showpoint (noshowpoint) to printed (or not) the decimal point.
std::fixed, std::scientific, std::hexfloat, std::defaultfloat to choose in between several common notations.
std::setprecision(int n) to choose how many decimal digits will appear.
Default precision is 6.
By default (if you don't set correct state), if your double value (say 8.0 or 8.5) can be printed shortly it will, thus 8 (or 8.5).
See : https://en.cppreference.com/w/cpp/io/manip/setprecision and https://en.cppreference.com/w/cpp/io/manip/fixed
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
Below you can find a basic C++ exercise with a for loop, the question is: what is the value of i after the loop runs. (Apparently, the value is 5.)
My question, on the 5th run (i=5), the value of a is 100, shouldn't the loop stop since the condition is a<100? Isn't the condition checked after a is multiplied with 10? (so after a is already 100)
If I check the value of a after the loop exit, it will be 1000. I am confused. Why does the loop not stop at 100?
#include <iostream>
using namespace std;
int main(void) {
float a;
int i = 0;
for(a = 0.01; a < 1e2; a *= 1e1)
++i;
return 0;
}
The exercise is designed to show that float (and double etc., floating point numbers in general) do not have the exact decimal value as what you see in the program text.
0.01 (decimal) cannot be exactly represented in the binary floating point format used, therefore multiplying 10 five times will not yield exactly 100.0.
See also: Floating point inaccuracy examples
You can't tell exactly what will happen with this code without knowing the details of the floating point implementation on your platform; the C++ standard leaves this intentionally flexible.
In essence 0.01 could be an approximation for the closest float to that double literal. So the stopping conditional a < 1e2 could be met prematurely or otherwise.
Note that along with 0.01, 1e1 is a literal of type double.
So the conversions to float are complicating things further. Then there is floating point strictness to consider.
Cut a long story short: don't use a floating point as the "index" in a loop.
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 5 years ago.
Improve this question
First code
double pi=3.14159,a=100.64;
cin>>a;
double sum=(a*a)*pi;
cout <<fixed<<setprecision(4)<<"Value is="<<sum<<endl;
return 0;
the value is =31819.3103
second code
float pi=3.14159,a=100.64;
float sum=(a*a)*pi;
cout <<fixed<<setprecision(4)<<"Value="<<sum<<endl;
return 0;
the value is =31819.3105
why the difference between two value ?
In both float and double (and all other floating-point types available in c++) the values are represented in floating-point form: to store x = m * 2^p, the values m and p are written to memory.
Obviously, not all real numbers can be represented in such form (especially given that the maximum length of m and p is limited). All the numbers that cannot be represented in such form are rounded to one of the nearest neighbours. Since both 3.14159 and 100.64 are infinite fractions in the binary system, both of them are rounded, and when you write a = 3.14159, a is really a bit different.
Subsequently, the result of some expression calculation on the rounded values is not precise and may vary if we use a different rounding mode, that's why you see the result you see.
Probably, the value obtained by using double is more precise as double on most architectures and compilers uses more digits of mantissa. To achieve even more precision, consider using long double.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I apologize for asking yet another rounding question. However, all the search has not yielded a satisfactory solution to my problem. The only possible answer is that what I am looking for may not be possible at all. Just wanted to make sure if the experts think the same.
So, here is my sample code:
double Round(double dbVal, int nPlaces)
{
const double dbShift = pow(10.0, nPlaces);
return floor(dbVal * dbShift + 0.5) / dbShift;
}
main()
{
string sNum = "1.29585";
double dNum = stod(sNum);
int iNumDecimals = 5;
double dRoundedNum = Round(dNum, iNumDecimals);
}
The number sNum is read as a string from a file. For example, the number in the file is 1.29585. I convert it to double using stod. dNum comes out to be 1.295849999999.... I would like to get back 1.29585 in double. Using a Round function as shown above does not help. The round function also returns 1.295849999999....
Is it possible to get back the exact 1.29585 at all? Any other possible solution?
Thanks in advance for any advice.
Your number is rounded to the closest representable double to the number you provided ( 1.29585 ). To 17 places, it is: 1.29584999999999995
The next largest representable double-precision number is 1 / 252 larger than that: 1.29585000000000017.
That's roughly 1 part in 5 quadrillion. An error of that magnitude, scaled to the circumference of the entire solar system, would only be about 8 centimeters.
So, in terms of rounding, the double you have is correctly rounded to the nearest representable binary value.
By default, floating point numbers are stored in binary. Just as you can't express 1/3 as an exact decimal fraction (you can approximate it with "0.33333333", extending out the 3s until you get sick of it), you can't express all round decimal values exactly in binary.
If you're curious what the above two values look like in binary: (You can refer to the diagram and description here to understand how to interpret that hexadecimal value if you are interested.)
1.29584999999999995 == 0x3FF4BBCD35A85879
1.29585000000000017 == 0x3FF4BBCD35A8587A
For your zillions of calculations, this approximate representation should cause no problem, unless you're computing a series of values that need to be rounded to an exact number of decimal places. Typically, that's only necessary if you're computing actual bank transactions or the like. Bankers want decimal rounding, so that their computations today match the way computations were done 100 years ago so that they have continuity between the pre- and post-computer eras, not because they're magically more accurate.
Double precision arithmetic carries 16 to 17 decimal positions of precision. The fact that it doesn't print as a nice round number of decimal digits doesn't mean it's inaccurate. If you compare the calculation the computer makes with double precision to the same calculation you'd do by hand (even with the aid of a standard calculator displaying 9 to 12 digits of precision), the computer's double precision arithmetic will generally come out ahead.
What you most likely want to do is to make sure to print out your final calculations to the appropriate number of decimal places. For example, you can use std::setprecision() from <iomanip> to control the precision of values printed via std::cout.
EDIT: If your application actually requires decimal arithmetic and decimal rounding, then you will need to look into decimal floating point support, either built into the compiler or in a 3rd party library. Some recent compilers do have support for this, and some processors even have hardware support for decimal floating point. GCC has decimal floating point extensions, for example, as does Intel's compiler. In contrast, Microsoft suggests finding a BCD library, it seems.
Try this way, i donĀ“t remember the format for double right now, i use float.
float num;
sscanf("1.29585", "%f", &num);
std::cout << num << std::endl;
The "I whipped it up in Haskell and translated it" answer:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double d = 1.2958499999999;
cout << setprecision(15) << d << endl;
cout << setprecision(15) << double(round(d * 1e5) / 1e5) << endl;
return 0;
}
// outputs:
// 1.2958499999999
// 1.29585
It is hardly a general answer, but it is correct to the letter of the question. I highly recommend understanding the evil that is IEEE floating point using e.g. Jim Buck's reference rather than putting this hack to any great use.
I recently picked up the c++ programming language, and I'm trying to calculate the digits of 'e' for a Calculus Project at school. I'll paste the pgoram that I've written below. It's based on e= lim(1+1/x)^x, as x-> infinity. In this program, I set x=100,000. I also set x=1,000,000 and noticed that the answers are somehow being subjected to a round-off error, instead of becoming longer in length.
Program:
#include <iostream>
#include <math.h>
using namespace std;
long double sum;
int main()
{
long double x=100000;
sum= (pow((1+(1/x)),(x)));
cout<<sum;
}
Any tips/ advice in making it print out more digits would be great. Thanks in advance.
On the first hand long double is limited in the number of digits it can produce, and because of how the real numbers are implemented it won't produce exact results.
But, to answer your question you can set cout's precision by doing
cout.precision(15);
cout << sum;
Also see this answer for more explanations and details see
How do I print a double value with full precision using cout?
Double in c++ is a floating point number. For accurate calculation like this you need use decimal number.
See this answer about decimal in cpp