英文:
Java different situation division
问题
如何在Java中对两个数进行除法,并在两种不同情况下得到不同的类型:
- 如果可能,得到int(例如6 / 2)
 - 否则,得到float(6 / 4)
 
代码如下:
int a;
int b;
float div = (float) a / b;
其中a和b都是整数。(例如,如果可以得到2,我不希望得到2.0)
英文:
How to divide two numbers in Java and get to different types in two different situations:
- Get int if it is possible(for example 6 / 2)
 - Otherwise, get float(6 / 4)
 
Code like this:
int a;
int b;
float div = a / b;
a and b are integers. (For example, I don`t want to get 2.0 if it is possible to get 2)
答案1
得分: 1
你还可以通过取模运算符来检查除法是否为整数。
int a = 6;
int b = 4;
if (a % b == 0) {
    System.out.print(a / b);
} else {
    System.out.print((float) a / b);
}
如果除法 a % b 等于 0,则表示除法是整数。如果不等于 0,则是一个分数,你可以将操作数中的一个(a 或 b)转换为浮点数,以获得表示分数结果的小数。
输出:
1.5
英文:
You can also just check with the modulo operator if the division is whole - numbered.
int a = 6;
int b = 4;
if(a % b == 0) {
    System.out.print(a/b);
}
else  {
    System.out.print((float)a/b);
}
If the division a % b equals 0 the division is whole numbered. If not then it's a fraction and you can cast just one of the operands(a or b) to a float to get the decimal representing the fraction result.
Output:
1.5
答案2
得分: 0
尝试将 float 转换为 int 并比较结果,如果相同,则打印整数,否则使用浮点数:
public class Main {
    public static void main(String[] args) {
        int a = 6;
        int b = 3;
        getDivisionResult(a, b);
        b = 4;
        getDivisionResult(a, b);
    }
    private static void getDivisionResult(int a, int b) {
        float div = (float) a / b;
        int rounded = (int) div;
        if (rounded == div)
            System.out.println(rounded);
        else
            System.out.println(div);
    }
}
输出:
2
1.5
英文:
Try casting the float to an int and compare the results, if it's the same, then print the integer, otherwise, use the float:
public class Main {
	public static void main(String[] args) {
		int a = 6;
		int b = 3;
		getDivisionResult(a, b);
		b = 4;
		getDivisionResult(a, b);
	}
	private static void getDivisionResult(int a, int b) {
		float div = (float) a / b;
		int rounded = (int) div;
		if(rounded == div)
			System.out.println(rounded);
		else
			System.out.println(div);
	}
}
Output:
2
1.5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论