Why a+=b*pow(10,c-i-1) == 99 c++? [duplicate] - c++

This question already has answers here:
Why pow(10,5) = 9,999 in C++
(8 answers)
Closed 4 years ago.
I wrote this code and first time of loop result is 99. Why is result 99, when it should be 100?
#include <iostream>
#include<math.h>
using namespace std;
int main ()
{
int skt = 0;
int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
skt = skt + (sk[i]*pow(10.0,nsk-i-1));
cout <<" "<<skt<<endl;
}
}
the result of this code
99
119
127
,but if I use library cmath it is correct answer
#include <iostream>
#include<cmath>
using namespace std;
int main ()
{
int skt = 0;
int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
skt = skt + (sk[i]*pow(10.0,nsk-i-1));
cout <<" "<<skt<<endl;
}
}
the result of this code
100
120
128
Could anybody explain why?

The math.h and cmath versions of pow are slightly different. Basically there are more supported inputs for the cmath version. You can compare the two at these links.
math.h and cmath

As people have commented, it's probably related to variable type conversion and floating point errors. Pow operates on doubles, which can have floating point errors. Chances are pow is returning a value like 99.9999999 which is then being converted to an integer. Since the integer conversion truncates instead of rounds, you get 99.

from this link cplusplus.com
Additional overloads are provided in this header ( cmath ) for other combinations of arithmetic types (Type1 and Type2): These overloads effectively cast its arguments to double before calculations, except if at least one of the arguments is of type long double (in which case both are casted to long double instead).
I bet if you cast it it would be correct in math.h

Related

Number of permutations calculation in c++ [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 6 months ago.
I am learning c++ and having a bit of trouble with my homework.
We have to write code using the double variable type and use two variables to calculate the number of permutations of the potential team arrangements…
The question specifies that there are 18 people in the group and you want to divide the group into teams of 3 members.
This is my current code:
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
int fact(int n) {
if (n == 0) return 1;
if (n > 0) return n * fact(n - 1);
}
int main()
{
double n = 18.0;
double r = 3.0;
double answer = fact(n) / (fact(r) * fact(n - r));
cout << “The number of arrangements = “ << answer << endl;
system(“pause”);
return 0;
}
When I run the code I am receiving “The number of arrangements = 1”
This is not the correct answer. Can someone please help me figure out what I am doing wrong?
Thanks!
Your fact function is returning an int, not a double.
Since your factorial function is returning an int, fact(n) is an int, and fact(r) * fact(n - r) is also an int.
Together, they will perform integer division, i.e. floor division, not true division.
Edit: Looked at the code again, I realized the problem wasn't integer division, it was the fact that int overflowed, where as double wouldn't overflow until 171!.

About the pow function in C++ [duplicate]

This question already has answers here:
Why does pow(n,2) return 24 when n=5, with my compiler and OS?
(4 answers)
Closed 6 years ago.
I just tried three pieces of code:
#include<cstdio>
#include<cmath>
#include<cstring>
int main()
{
int a = 3;
int b = pow(10,a);
printf("%d",b);
return 0;
}
//Output:1000
#include<cstdio>
#include<cmath>
#include<cstring>
int main()
{
int a = 3;
int b = pow(10,a-1);
printf("%d",b);
return 0;
}
//Output:99
#include<cstdio>
#include<cmath>
#include<cstring>
int main()
{
int a = 3;
int b = pow(10,a-2);
printf("%d",b);
return 0;
}
//Output:10
I would like to know why the second block of code will output 99, is it because of floating point precision? Or is it because I should use float numbers in the pow function?(Such as 10.0)
I'm usually confused about the accuracy of C++, I will be grateful for your help.
For integer exponents the following template can be very handy:
template <typename T> inline constexpr T pow( T base, int exponent )
{
return (exponent == 0) ? static_cast<T>(1.0) : ( (exponent>0) ? base*pow(base, exponent-1) : pow( static_cast<T>(1.0)/base, -exponent ) );
}
If you plan to use it with a C++ standard prior C++11, just remove the constexpr keyword.
Conversion of a floating-point value to an integer is done by truncation — you get the next integer closest to zero. If pow is imprecise and too low, then truncation will exacerbate it.
lround(pow(10,2)) might be more appropriate.

Conversion from double to integer [duplicate]

This question already has answers here:
C++: How to round a double to an int? [duplicate]
(5 answers)
round() for float in C++
(23 answers)
Closed 8 years ago.
I am stuck in problem where the double number is not getting properly converted to integer.
In this case->
int x=1000;
double cuberoot=pow(x,(1/(double)3));
int a=cuberoot;
cout<<"cuberoot="<<cuberoot<<endl;
cout<<"a="<<a<<endl;
Output:
cuberoot=10
a=9
Why here a=9 and not 10?
Any solution to this problem??
Also I don't want to round the value..if a=3.67 then it should be converted to 3 only
and not 4.
Because the cuberoot is very close to 10 but not quite 10. std::cout truncates and rounds the number to 10, but a double to integer conversion will strip the decimal which is why a = 9. To solve this problem, you can use std::round():
int a=round(cuberoot);
Try this and see why!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(){
int x = 1000;
double cube = pow(x, 1.0/3.0);
int a = cube;
cout<<"cube="<< fixed << setprecision(16) << cube<<endl;
cout<<"a="<<a<<endl;
}

output does not meet my expected result, how to fix it? [duplicate]

This question already has answers here:
How to get fractions in an integer division?
(2 answers)
Closed 9 years ago.
my expected result is average=73.5 ,i have set the type of average as double but it result 73 what's the problem?
#include <iostream>
using namespace std;
int main(){
int x=0;
int total=0;
double average=0;
int counter=0;
cout<<"Question 1"<<endl<<"Enter integer(-100 to end);";
cin>>x;
if (x!=-100)
{
for(;x!=-100;counter++)
{
total=total+x;
cin>>x;
}
average = total/counter;
}
cout<<"The average is:"<<average<<endl;
return 0 ;
}
You're doing integer calculations. Cast one of the integers to double:
average = ((double)total)/counter;
Integer operations yield integers as result. In C and C++ they never yield floating point results. You need to involve a floating point value in the computation, e.g.
average = (1.0 * total) / counter;

What is the C++ function to raise a number to a power?

How do I raise a number to a power?
2^1
2^2
2^3
etc...
pow() in the cmath library. More info here.
Don't forget to put #include<cmath> at the top of the file.
std::pow in the <cmath> header has these overloads:
pow(float, float);
pow(float, int);
pow(double, double); // taken over from C
pow(double, int);
pow(long double, long double);
pow(long double, int);
Now you can't just do
pow(2, N)
with N being an int, because it doesn't know which of float, double, or long double version it should take, and you would get an ambiguity error. All three would need a conversion from int to floating point, and all three are equally costly!
Therefore, be sure to have the first argument typed so it matches one of those three perfectly. I usually use double
pow(2.0, N)
Some lawyer crap from me again. I've often fallen in this pitfall myself, so I'm going to warn you about it.
In C++ the "^" operator is a bitwise XOR. It does not work for raising to a power. The x << n is a left shift of the binary number which is the same as multiplying x by 2 n number of times and that can only be used when raising 2 to a power, and not other integers. The POW function is a math function that will work generically.
You should be able to use normal C methods in math.
#include <cmath>
pow(2,3)
if you're on a unix-like system, man cmath
Is that what you're asking?
Sujal
Use the pow(x,y) function: See Here
Just include math.h and you're all set.
While pow( base, exp ) is a great suggestion, be aware that it typically works in floating-point.
This may or may not be what you want: on some systems a simple loop multiplying on an accumulator will be faster for integer types.
And for square specifically, you might as well just multiply the numbers together yourself, floating-point or integer; it's not really a decrease in readability (IMHO) and you avoid the performance overhead of a function call.
I don't have enough reputation to comment, but if you like working with QT, they have their own version.
#include <QtCore/qmath.h>
qPow(x, y); // returns x raised to the y power.
Or if you aren't using QT, cmath has basically the same thing.
#include <cmath>
double x = 5, y = 7; //As an example, 5 ^ 7 = 78125
pow(x, y); //Should return this: 78125
if you want to deal with base_2 only then i recommend using left shift operator << instead of math library.
sample code :
int exp = 16;
for(int base_2 = 1; base_2 < (1 << exp); (base_2 <<= 1)){
std::cout << base_2 << std::endl;
}
sample output :
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
It's pow or powf in <math.h>
There is no special infix operator like in Visual Basic or Python
#include <iostream>
#include <conio.h>
using namespace std;
double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)
void main()
{
double x; //initializing the variable x and i
int i;
cout<<"please enter the number";
cin>>x;
cout<<"plese enter the integer power that you want this number raised to";
cin>>i;
cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}
//definition of the function raiseToPower
double raiseToPow(double x, int power)
{
double result;
int i;
result =1.0;
for (i=1, i<=power;i++)
{
result = result*x;
}
return(result);
}
Many answers have suggested pow() or similar alternatives or their own implementations. However, given the examples (2^1, 2^2 and 2^3) in your question, I would guess whether you only need to raise 2 to an integer power. If this is the case, I would suggest you to use 1 << n for 2^n.
pow(2.0,1.0)
pow(2.0,2.0)
pow(2.0,3.0)
Your original question title is misleading. To just square, use 2*2.
First add #include <cmath> then
you can use pow methode in your code for example :
pow(3.5, 3);
Which 3.5 is base and 3 is exp
Note that the use of pow(x,y) is less efficient than x*x*x y times as shown and answered here https://stackoverflow.com/a/2940800/319728.
So if you're going for efficiency use x*x*x.
I am using the library cmath or math.h in order to make use of the pow() library functions that takes care of the powers
#include<iostream>
#include<cmath>
int main()
{
double number,power, result;
cout<<"\nEnter the number to raise to power: ";
cin>>number;
cout<<"\nEnter the power to raise to: ";
cin>>power;
result = pow(number,power);
cout<<"\n"<< number <<"^"<< power<<" = "<< result;
return 0;
}
use pow() function in cmath, tgmath or math.h library.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
cout << pow(a,b) << endl; // this calculates a^b
return 0;
}
do note that if you give input to power as any data type other than long double then the answer will be promoted to that of double. that is it will take input and give output as double. for long double inputs the return type is long double. for changing the answer to int use,
int c=(int)pow(a,b)
But, do keep in mind for some numbers this may result in a number less than the correct answer. so for example you have to calculate 5^2, then the answer can be returned as 24.99999999999 on some compilers. on changing the data type to int the answer will be 24 rather than 25 the correct answer. So, do this
int c=(int)(pow(a,b)+0.5)
Now, your answer will be correct.
also, for very large numbers data is lost in changing data type double to long long int.
for example you write
long long int c=(long long int)(pow(a,b)+0.5);
and give input a=3 and b=38
then the result will come out to be 1350851717672992000 while the correct answer is 1350851717672992089, this happens because pow() function return 1.35085e+18 which gets promoted to int as 1350851717672992000. I suggest writing a custom power function for such scenarios, like:-
long long int __pow (long long int a, long long int b)
{
long long int q=1;
for (long long int i=0;i<=b-1;i++)
{
q=q*a;
}
return q;
}
and then calling it whenever you want like,
int main()
{
long long int a,b;
cin >> a >> b;
long long int c=__pow(a,b);
cout << c << endl;
return 0;
}
For numbers greater than the range of long long int, either use boost library or strings.
int power (int i, int ow) // works only for ow >= 1
{ // but does not require <cmath> library!=)
if (ow > 1)
{
i = i * power (i, ow - 1);
}
return i;
}
cout << power(6,7); //you can enter variables here