Why can't the type of x/y/z be int?(Floating point numbers and mathematical operators)

I have a question about Floating point numbers and mathematical operators

#include <iostream>;
int main() {
	double x = 10;
	double y = 5;
	double z;
	z = (x + 10) / (3 * y) ; //Why can't the type of x/y/z be int?
	std::cout << z;

	return 0;
}

x and y can be int
but the z = 3.333
so z should always be double

Well double is for declaring numbers with decimal points or predicting they might have a decimal point and in this exercise Mosh tells us that the value of z is 1.333, so we need to declare all their types to double, well if you don’t like it then you can set y to integer and it won’t make a difference.

A tip for you after seeing your code:

It is better as a programmer to simplify and try to make your code as short and simple as possible so in this case you can put the equation of z directly where you declared the z double, so you can basically do this:

#include <iostream>

int main() {
    double x = 10;
    double y = 5;
    double z = (x + 10) / (3 * y);
    std::cout << z;
   
    return 0;
}

I am afraid that is wrong information, if you are calculating between 2 variables that are set to an integer value the answer cannot be output as a double or float, so you need to keep in mind that at least two of the values’ meaning x and z or y and z (that is personal preference) should be set to float or double types.

Well done! Thank you so much!

1 Like

You’re Welcome Brother :)