c - Is i=i+1 an undefined behaviour? -
i'm using codeblocks , giving different output other compilers , can't find solution it.what's undefined behaviour in program , there solution avoid it?
this code print nth number in number system 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 : %d",value); } it works fine numbers upto 6..and output numbers greater 6 1 less should be. e.g. if n=7,output=332 should 333.
edit : provided full code braces.
there no undefined behavior in code. i=i+1; well-defined behavior, not confused i=i++; gives undefined behavior.
the thing cause different outputs here floating point inaccuracy.
try value += 4 * (int)nearbyint(pow(10,i)); , see if makes difference.
Comments
Post a Comment