Java不同情况分割

huangapple go评论73阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月20日 17:02:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63977241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定