Need help with this simple code involving typecasting please

+2 Michiel Becking · January 5, 2016
Yo dudes,

Why won't this code run?

int main()
{
   int years = 0;
   int balance = 1000;

   while(years <= 3) {
        (float)balance *= 1.03;
        years++;
    }
    printf("Balance is now : %.2f", (float)balance);

    return 0;
}

Line 10 is wrong, I know I can just make it float at the beginning, but still I was wondering???
Please help, thanks




EDIT:
I have another question : When I run this code:

int main()
{
   int variable;

   for(variable=0; variable<=80; variable+=8){
    printf("Variable is %d \n", variable);
   }

   printf("Variable:%d \n",variable);

   return 0;
}




the last printf statement will print out 88 (while the last one in the for loop will print 80),
is this because when it is 80, it will still increment by 8? but then it is 88 so it doesnt meet the criterium to execute the code between the brackets? is this the reason??

thanks :)

Post a Reply

Replies

Oldest  Newest  Rating
+1 Laura Lee · January 6, 2016
Your first mistake is an lvalue cast.

Your second mistake is <=. Variable will reach 80, add 8, check if 88 is <= 80, and terminate.
0 Michiel Becking · January 7, 2016
Thanks for your answer.

Can you please elaborate the first mistake?

You can't typecast values that are on the left side of the equation ???

Is this true ?
  • 1

C

107,106 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator