"In the previous chapters, we have performed calculations involving integers with integers and real numbers with real numbers."
I have never performed calculations involving a mixture of integers and real numbers.
Mixed calculation with integers and real numbers refers to calculations such as 1.03 × 9.
This calculation involves the multiplication of a real number by an integer.
What would the answer be in a case like this?
To conclude, in this case, the result will be a real number.
In C, when calculating with integers and floating-point numbers, the result is converted to a floating-point number.
This is because converting the result to an integer would eliminate the real part.
The following program is an example of actually calculating 1.03 x 9.
#include <stdio.h>
int main(void)
{
printf("%f\n", 1.03 * 9);
return 0;
}
The results of this program's execution are as follows:
I think you can see that the answer has been converted to a real number.
I also tried displaying it as an integer using the %d specifier, and the result was as follows.
It's clear that the values are incorrect.
Please note that the appearance of this display may vary depending on your computer environment and may not be exactly the same.
In calculations involving integers and real numbers, we have found that the answer is a real number.
However, there may be instances where an integer answer is more convenient.
For example, the formula for calculating consumption tax is amount x 1.05 (as of September 14, 2004),
"Normally, performing this calculation results in a real number as the answer."
It's unusual for amounts to include decimals.
If there were a way to convert a real number to an integer, this problem would be solved.
C has a feature called
casting for forcibly converting data types.
【Type casting】
Forceful type conversion
Here's how to use type casting.
(Type name for conversion) numeric or variable name
For example, if you want to convert a real number like 1.05 to an integer, you can do so by using (int)1.05.
1.05 is converted to an integer and treated as 1.
If you use this method, you can also calculate consumption tax.
The following program is an example of calculating the consumption tax for a 360 yen item.
#include <stdio.h>
int main(void)
{
printf("%d\n", (int)(1.05 * 360));
return 0;
}
The results of this program's execution are as follows:
"The reason this program is putting parentheses around 1.05 x 360 is..."
"This is because without parentheses, 1.05 would be evaluated first and become 1."
Regardless of this specific example, the order of operations is important to reduce computer-specific calculation errors.
Furthermore, the results of real number calculations and their converted integer values may vary depending on the compiler and computer type.
There might be slight variations, so it won't always be exactly 378.
Casting can, of course, also be used with variables, and the usage is the same.