for school i need to wright a program that reads a float number and then displays the largest integer that can fit , ex read in 12.123 should display out 12 without the decimal points. to my understanding (int) cant display decimal but float can so here is my code, for some reason tho it does not matter what float i input it always outputs 96 for me.... i dont understand
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
float num1;
int num2;
// Enter a number with decimals
cout << " Enter a percise number " << endl;
cin >> num1;
num1 = num2;
cout << " Your New Number is " << num2 << endl;
return (0);
}
yup, you are correct. why is that tho ? why is saying num1=num2 bad but num2=num1 correct...
do you have an idea as well as to why it would originally display 96 for me ?
When you declare a variable and dont assign any value to it, the variable points to some local of your memory, and there can be any value, if you turn off your computer and turn on again, you have a chance to get any other random value instead of 96
i see. that makes sence about the 96
im still a tad confused as to why saying num1 = num2 didnt work but num2 = num 1 did
to me its like saying the same thing .
#include <iostream>
usingnamespace std;
int main()
{
float num1;
int num2=0;//<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Enter a number with decimals
cout << " Enter a percise number " << endl;
cin >> num1;
num1 = num2;
cout << " Your New Number is " << num2 << endl;
return (0);
}
Assignment does not mean any mathematical equivalence or any sort of bijective property. Variables are places that hold a value.
1 2 3 4 5 6 7 8 9
int a = 3, b = 4; //Now a holds value 3 and b holds value 4
a = b; //This means that we take the value in b and make a hold the same value and since b is not changed after this a holds 4 and b holds 4
//Now have the situation other way around
a = 3; //Let us have the starting position i.e. a is 3 and b is 4
b = a; //This results that b now holds the value of a which is 3 and since a is not changed after this both variables hold value of 3
As you can see the order of an assignment has a large importance.
The = symbol is not an ordinary equals sign, like in an equation. It is the assignment operator.
The way it works is to first of all evaluate the result of whatever is on the right hand side of the = sign. After that, store the result in the variable named on the left.
example:
1 2
int x;
x = 2 + 3;
first, the expression 2+3 is evaluated, giving 5. Then the result is stored in the variable x.
but you cannot do this:
1 2
int x;
5 + 4 = x;
here, it would evaluate the expression x and then try to store the result ... where? It isn't possible in this case.