Defining the same variable twice in the same scope? (C)
One of my homework assignments asks why the value of f and g are different. My guess was that f was already declared as 3.0 so it stays that way even though it was defined again, but the second definition of f doesn't make sense to me (defining a word by using the word itself).
code:
#include <stdio.h>
int main(void) {
int i,j;
float f,g;
i = 5; j = 2;
f = 3.0;
f = f + j / i;
g = (f + j )/i;
printf("value of f,g is %f,%f\n", f,g);
return 0;
}
>>17755074
How new are you to this?
Also there is nothing wrong with the code, only with your interpretation of it.
Would it not be better to ask /g/?
>>17755111
very new. I'm taking an intro programming class online.
So if nothing is wrong with the code, how can f be defined twice? what is the value of f then?
>>17755261
I believe the correct expression is 'assigned a value', rather than defined.
Also almost always when you encounter '=' sign you will have to read the instruction from right to left.
So f = 3.0; means assign 3.0 to f.
Then f = f + j / i; means assign the old value of f which is 3.0 plus j divided by i (j / i is 0 because integer division magic aint gotta explain shit(Actually its because there is no whole number as a result of division only a fractional part)) to new f.
So its assign 3 + 0 to new f.
Then new f is also 3.
But not because the compiler ignored the second assignment but because second assignment is literally 3 + 0.
This is literally middle school math.
How do you not understand algebra this hard?
>>17755283
Nothing to do with algebra.
>>17755280
jesus if only my textbook went into more detail like you did, that was extremely helpful. How I've been taught, assigned value and defined are synonymous for each other, but assigning a value makes a lot more sense in this case.
Thank you very much
>>17755283
its not the math i didnt understand, its that i didnt know you could reassign values to a variable or however you want to put it.
I don't really know what it is you don't understand so i'm just going to step through it all for you.
okay first off:
printf() is a defined in <stdio.h> so you'll need to include that. If you want to use <iostream> you need to use cout >>
onto the code.
on this line:
f = f + j / i
you are assigning the value of (3.0 + 2 / 5) to f.
i and j are integers though, so 2 / 5 is 0 (it gets floored)
the integer math is done first and then the value 0 is cast to a float and added to the float value of 3.0. so f = 3.0 + 0 = 3.0
so pretty much this operation does nothing to f, in that it's still 3.0 by the end of it.
g = (f + j) / i
g = (3.0+2) / 5
= 5.0 / 5 = 1.0
here you divide a float by an int, which means the int is first cast to a float and then the division is done as if with two floats.