0

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

UTPAL
  • 31
  • 11
  • 4
    Considering that a 32-bit `int` can hold a 10-digit decimal number, your string is not long enough. There is a good reason for [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) There is no need to use `pow`, it won't be accurate. To build a value, you simply multiply the current value by `10` and add the next digit. So `d = d * 10 + (str[i] -'0');` – Weather Vane Apr 22 '20 at 18:39
  • maybe `pow(10, 2)` returns 99.99999996535764 – pmg Apr 22 '20 at 18:40
  • the result depends on the compiler of the IDE ? – bruno Apr 22 '20 at 18:41
  • Related: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Barmar Apr 22 '20 at 18:45

1 Answers1

1

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')
dbush
  • 205,898
  • 23
  • 218
  • 273
  • whoa.. it worked. But how come on online compiler results were coming correct before correcting code? – UTPAL Apr 22 '20 at 18:53
  • 2
    @UTPAL Different implementations have their own version of `pow`, each of which handles rounding slightly differently – dbush Apr 22 '20 at 19:03