[Study Notes 1] The use of C++ division sign "/"

In mathematical calculation, use "/" to get the actual result, for example: 4/5=0.8.

In C++, different results are obtained according to the types of the two numbers: Example a/b

  1. Scenario 1:

When a and b are integer types such as int, long, char, the result of the division operation is the integer part of the obtained quotient, for example: 180/100, the result is 1;

	int a = 180;
	int b = a / 100;
	cout << b << endl;
	
    #结果为1
  1. Scenario 2:
    When one or both of a and b are decimal (float, double) numbers, the result of the quotient is the actual result. For example: 180.0/100, the result is 1.8;
	float a = 180.0;
	float b = a / 100;
	cout << b << endl;
	
    #结果为1.8

But when the two input numbers are both integers, how can we get the actual result?
Example: 180/100

  1. Method 1:
    Add ".f" after the dividend
float c = 180 / 100.f;

#结果为1.8
  1. Method 2:
    Convert one of the integers to float or double type;
	int a = 180,b = 100;
	float c = 0;
	c = (float)a / b;

	#结果为1.8

Guess you like

Origin blog.csdn.net/weixin_52703185/article/details/116939740