I'm using codeblocks and it is giving a different output to other compilers and I can't find a solution to it.What's the undefined behaviour in this program and is there any solution to avoid it?
This is the code to print the nth number in a number system with only 3 & 4.
#include<stdio.h>
#include<math.h>
int main(void)
{
int n,i,value;
scanf("%d",&n);
value=i=0;
while(n>0)
{
if((n%2)==0)
{
value+=4*pow(10,i);
}
else
{
value+=3*pow(10,i);
}
n=(n-1)/2;
i=i+1;
}
printf("\nThe number is : %d",value);
}
It works fine for numbers upto 6..And the output for numbers greater than 6 is one less than what it actually should be. E.g. if n=7,output=332 where it should be 333.
EDIT : Provided the full code with braces.
There is no undefined behavior in this code.
i=i+1;
is well-defined behavior, not to be confused withi=i++;
which gives undefined behavior.The only thing that could cause different outputs here would be floating point inaccuracy.
Try
value += 4 * (int)nearbyint(pow(10,i));
and see if it makes any difference.