Reputation: 31
The question was: Define a function getint(), which would receive a numeric string from keyboard, convert it to an integer number and return the integer to the calling function.
My code is:
#include<stdio.h>
#include<math.h>
#include<string.h>
int getint();
int main()
{
int a;
a = getint();
printf("you entered %d",a);
return 0;
}
int getint()
{
char str[10];
printf("Enter number: ");
gets(str);
int d=0,len = strlen(str),r = len-1;
for(int i=0;str[i] != '\0';i++,r--)
d += (str[i]-48)*pow(10,r);
return d;
}
while I run this program from sublime text or code block the output was coming wrong
output(from sublime and codeblocks):
Enter number: 123 you entered 122
But when I used onlinegdb.com/online_c_compiler the output was coming correct
So how can output differ from compiler to compiler for the same program
Upvotes: 0
Views: 61
Reputation: 225007
The pow
function works with floating point numbers. As such, the result may not be exactly equal to what you expect the numerical result to be. For example, pow(10,2)
could output a number slightly larger or slightly smaller than 100. If the result is just below 100, the fractional part gets truncated and you're left with 99.
Rather than using pow
for an integer power, just multiply the current value of d
by 10 before adding the value for the next digit.
d = 10 * d + (str[i]-'0')
Upvotes: 1