A variable is a letter
(or name) that represents a value. The number 576.50 above
is the income
received from selling baked goods. We could use the letter X to represent this number.
But the letter X isn't really the clearest choice - we could use I or INC to represent INCOME =
576.50.
Now rather than writing 576.50 over and over again, we could just
write INC, or just I .
This has several advantages:
Here is a better version of the program, written using variables.
float i = 576.50;
float s = 87.50;
float c = 55.95;
float o = 92.00;
float profit = i-(s+c+o);
println("Profit = " + profit);
println("Brazil = " + 0.6 * profit);
println("Thailand = " + 0.3 * profit);
println("Parents = " + 0.1 * profit);
This might appear more complex, due to words like "float", and
because it's actually longer.Consistency is also
helpful. If you are going to use whole words for variables -
e.g. profit -
then do that all the time.
What does "float" mean?
"float" is a variable type.
This forces the numbers stored in the variables to be treated as
decimals
rather than integers. As a result, you can write the
following and get a correct answer:
float money = 700;
float people = 8 ;
float share = money / people;
println("Each person gets " + share + " Euros"); // ==> 87.50
Since all the variables are float
types, the division will be done using decimals and give a correct
answer.
It doesn't matter that there are no decimals in 700 or 8.
The word float FORCES
these to be treated as decimals.
READ each program below. PREDICT what you think it will
print. Then RUN it and check your answer.
float age = 15; |
float x = 3; |
float price = 7.50; |
float money = 123; |
Each of the following programs contains errors. Fix the errors
and make each program run correctly.
price = 14.95; |
float euros = 150; |
float hours = 8; |
float radius = 7; |