Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Power function returns 1 less result

Whenever I input a number in this program the program return a value which is 1 less than the actual result ... What is the problem here??

#include<stdio.h>
#include<math.h>
 int main(void)
 {
     int a,b,c,n;

     scanf("%d",&n);

     c=pow((5),(n));

    printf("%d",c);

 }

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

pow() returns a double, the implicit conversion from double to int is "rounding towards zero".

So it depends on the behavior of the pow() function.

If it's perfect then no problem, the conversion is exact.

If not:

1) the result is slightly larger, then the conversion will round it down to the expected value.

2) if the result is slightly smaller, then the conversion will round down which is what you see.

solution:

Change the conversion to "round to nearest integer" by using rounding functions

c=lround(pow((5),(n)));

In this case, as long as pow() has an error of less than +-0.5 you will get the expected result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...