I was testing the pow() function in c++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << pow(8,(1/3)) << endl;
return 0;
}
For some reason, this returns 1. Why does this happen?
This is because 1/3 is evaluated in integers. The result of the division is 0, so pow(x, 0) produces 1.
Change the division to division in doubles like this:
cout << pow(8,(1.0/3)) << endl; // prints 2 as expected
Demo.
1/3 produces an integer result of 0
when you use integers as your input to the pow() function the computer truncates the output. If you input floating point numbers the error will be corrected
pow(8, 1/3) = 1
pow(8.0, 1.0/3) = 2
Related
This question already has answers here:
How to specify setprecision rounding
(4 answers)
Closed 1 year ago.
I'm doing my ICT homework and I ran into this problem: the decimals keep on getting rounded off when I print them. I've already included the <iomanip> header and used the fixed and setprecision manipulators, but it still keeps getting rounded off. Here's my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double num1 = 3.12345678
cout << fixed << setprecision (4);
cout << num1 << endl;
return 0;
}
When I run the program, "3.1235" comes out instead of "3.1234," which is the expected output according to my teacher. How do I prevent the fourth decimal from rounding off?
Expanding answer of #eerorika. You can use std::fesetround() to set rounding strategy, as in code below. It outputs 3.1234 as you wished. Possible values for this function's argument are FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD.
Try it online!
#include <iostream>
#include <iomanip>
#include <cfenv>
int main() {
double num = 3.12345678;
std::fesetround(FE_TOWARDZERO);
std::cout << std::fixed << std::setprecision(4) << num << std::endl;
}
Output:
3.1234
3.1234 is not the expected output, setprecision will round to the specified precision.
One solution to get 3.1234 is to round to the desired number of decimal places yourself (std::trunc just rounds towards zero):
#include <cmath>
...
std::cout << std::fixed << std::setprecision(4);
std::cout << std::trunc(num1 * 10000) / 10000 << endl;
If you want to prevent rounding i.e. you want to see more precision, you can use a higher value with setprecision.
If you want to round towards zero instead of rounding towards nearest, you can use the FE_TOWARDZERO rounding mode.
how would I make it so when i enter 2.785 for the input question the output will display the variable question as 2.79?
I tried using setprecision but for some reason it is not working unless i am doing it wrong
here is the user input question and what it should be:
Enter positive daily growth % (.1 must be entered as 10):
user enters "2.785"
output -> 0.02785
My desired output should look like:
desired output-> 2.79%
Any help is appreciated. I know it may seem simple to others but I have already tried looking online and everything I find just isn't making sense or doesn't work and I dont know what I am doing wrong.
Floating point arithmetic
The reason why it is challenging is that floating point cannot be represented accurately when you perform operations on them. See wikipedia article
It is a very intesting topic, if you have a bit of time, take a look at explanations about floating point and how its representation inside the computer.
If you are looking for the display only (only works for small decimals)
If you are just looking to display a small value you can use below code:
#include <cmath>
#include <iostream>
#include <iomanip>
#include <limits>
#include <sstream>
using namespace std;
string truncateAsString(double n, int precision) {
stringstream ss;
double remainder = static_cast<double>((int)floor((n - floor(n)) * precision) % precision);
ss << setprecision(numeric_limits<double> ::max_digits10 + __builtin_ctz(precision))<< floor(n);
if (remainder)
ss << "." << remainder;
cout << ss.str() << "%" << endl;
return ss.str();
}
int main(void) {
double a = 0.02785;
int precision = 100; // as many digits as you add zeroes. 3 zeroes means precision of 3.
string s = truncateAsString(a*100 + 0.5 / 100, precision);
return 0;
}
Looking for the true value?
Maybe you are looking for true value for your floating point, you can use boost multiprecision library
The Boost.Multiprecision library can be used for computations requiring precision exceeding that of standard built-in types such as float, double and long double. For extended-precision calculations, Boost.Multiprecision supplies a template data type called cpp_dec_float. The number of decimal digits of precision is fixed at compile-time via template parameter.
You need to use a custom library like boost/multiprecision because of the lack of precision for floating points, see my code below:
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
#include <limits>
#include <cmath>
#include <iomanip>
using namespace std;
using boost::multiprecision::cpp_dec_float_50;
cpp_dec_float_50 truncate(cpp_dec_float_50 n, int precision) {
cpp_dec_float_50 remainder = static_cast<cpp_dec_float_50>((int)floor((n - floor(n)) * precision) % precision) / static_cast<cpp_dec_float_50>(precision);
return floor(n) + remainder;
}
int main(void) {
int precision = 100; // as many digits as you add zeroes. 5 zeroes means precision of 5.
cpp_dec_float_50 n = 0.02785 * 100;
n = truncate(n + 0.5/precision, precision); // first part is remainder, floor(n) is int value truncated.
cout << setprecision(numeric_limits<cpp_dec_float_50> ::max_digits10 + __builtin_ctz(precision)) << n << "%" << endl; // __builtin_ctz(precision) will equal the number of trailing 0, exactly the precision we need!
return 0;
}
Output (both cases)
2.79%
NB: I add 0.5 / precision to the truncate function to force it to act like a rounding.
#include <iostream>
#include <cmath>
double buf[128 * 1024];
int main()
{
int i = 0;
unsigned long long n; // 64-bit unsigned integer
while (std::cin>>n) {
buf[i ++] = double(sqrt(n)); // store in buffer
}
i--;
while(i>=0){
printf("%lf\n",buf[i]); // When i am using this it works fine.
//std::cout<<buf[i]<<std::endl; // When i am using this line instead of printf function it shows wrong answer. why?
i--;
}
return 0;
}
I have compiled it with G++.
While I am trying to print the output with printf funtion then it is accepted. But when I am using cout function then it gives wrong answer. Why is it happened?
This code shows compilation error when i am compiling it in GCC7.1 . What is the reason of this?
Problem Link : https://acm.timus.ru/problem.aspx?space=1&num=1001
Using the << operator with std::cout rounds to 6 significant figures by default and uses scientific notation for large floating point numbers. To disable the scientific notation, include the <iomanip> header and use std::cout << std::fixed << buf[i];. Using std::fixed will also set the rounding to 6 digits after the decimal point.
I need help on how to format the output in C++ to show decimal places if there is any, or show the whole integer if there is no decimal point to show.
it should show 95.7 // When there is decimal
it should show 90 // When there is no decimal
I wrote:
cout << setprecision(1) << fixed;
It does not give me the expected output. Instead of printing 90, it prints 90.0
Assuming that you are performing division.
Using cout:
i) If the decimal part turn out to be .000000, then using cout will print just the integer (the whole number) part.
ii) If the decimal part turn out to be something other than .000000, then cout will print the decimal part as well.
Thus, in both the cases, cout will lead to the behavior that you require.
Using printf()
i) If the decimal part turns out to be .000000, then using printf() will print the integer, followed by the decimal part, e.g., 3.000000. In this case, you will manually have to handle it so that you get the output as just 3. You can follow different approaches, like converting to a string, using inbuilt functions, etc.
ii) If the decimal part is not .000000, then printf() will print the output like 3.123456.
Please see the code below. I am using the fact that if the remainder of division is 0, then it means that the decimal part is .000000 and typecasting the numbers to int before printing them. You might have to use a different approach as pointed above.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
double num1=270.0, num2=90.0;
cout<<num1/num2<<"\n"; //prints just 3
printf("%f\n", num1/num2); //prints 3.000000
if((int)num1%(int)num2==0) //means num1 is a multiple of num2. So decimal is .000000
printf("%d\n", (int)num1/(int)num2);
num2=91.0;
cout<<num1/num2<<"\n"; //prints 2.96703
printf("%f\n", num1/num2); //prints 2.967033
if((int)num1%(int)num2!=0)
printf("%f\n", num1/num2);
return 0;
}
Live demo here.
You can create a function that will convert the float to only one decimal place. Then test if the float is equal to its integral part (i.e. if 90.0 equals 90) then only print the integral part, otherwise print the float.
#include <iostream>
#include <math.h>
using namespace std;
void printFloat(float num) {
// convert num to properly rounded decimal with 1 decimal place
num = floor(num*10 + .5)/10;
// if the float equals the whole number, only show the whole number
if (num == (int)num)
cout << (int)num << endl;
else
cout << num << endl;
}
int main() {
float num1 = 90.0;
float num2 = 90;
float num3 = 90.00001;
float num4 = 95.7;
float num5 = 95.74;
float num6 = 95.75;
printFloat(num1); // prints 90
printFloat(num2); // prints 90
printFloat(num3); // prints 90
printFloat(num4); // prints 95.7
printFloat(num5); // prints 95.7
printFloat(num6); // prints 95.8
}
There will be two numbers in the input file which are between 1 ≤ n, m < 100.
I should display m to power n. When i use pow(x,y) function it cannot calculate big integers for ex ::: 12 to power 23 normally should show 6624737266949237011120128, but my code displays negative number. Can anyone solve this exercise ?
This is not very difficult to do without using external libraries. Store the digits of the number in a vector and multiply digit by digit (like you do in paper).
Example:
power(12,23):
Store as start->1->2->end
step 1 result: start->1->4->4->end
step 2 result: start->1->7->2->8->end
and so on...
Can you show your source code?
Use double is enough to store the result
Below is my test code for you reference:
#include <iostream>
#include <cmath>
using namespace std;
int main (int argc, char *argv[])
{
double result = pow (12, 23);
cout.precision (26);
cout << "Result: " << result << endl;
}
Try to store your base in a long double before calling pow :
long double base = 12;
long double result = pow(base, 23);
It is not required since C++11 though, you can get a good approximation like this :
#include <iomanip>
#include <iostream>
#include <cmath>
int main ()
{
std::cout << std::fixed << std::setprecision(0) << pow(99, 99) << std::endl;
}
Output :
369729637649726802192985226395427290145296428445515959701359650120802601667133273280053721002700400354392780458116125965728631706472588849812738072765460822138161108630185181415759762204338929270784
But it is an approximation, for instance Python2 code print 99 ** 99 outputs this :
369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899
To get an exact result in C++, you should look at some BigInt libraries.