英文:
Method for converting float to integer after checking
问题
我正在尝试对两个数字(称为A和B)执行多个操作。这两个数字通过单个字符串输入。所以我将它们转换为Double
值并对它们执行操作。
问题在于输出始终是double
。如果结果是整数,我希望答案是整数答案,例如2
而不是2.0
。
情况:
-
A= 2
和B= 2
(输入为字符串)=> 提取为浮点变量 => varA= 2.0,varB=2.0 当前结果 => 4.0(简单的*操作)最佳结果 =>4
-
A= 2.0
和B= 2.0
(输入为字符串)=> 提取为浮点变量 => varA= 2.0,varB=2.0 当前结果 => 4.0(简单的*操作)最佳结果 =>4.0
我查了一下,没有太大帮助。因为这些问题通常涉及到转换或精度。如果有类似或有帮助的问题的链接,我可能错过了也可以。我知道如何从float
转换为int
,但我正在寻找检查数字是否可以表示为整数的最佳方法。然后根据情况获取结果。
谢谢。
英文:
I am trying to perform multiple operations on two numbers (say A and B). These two numbers are getting inputted via a single string. So I am converting them into Double
values and performing an operation on them.
The poblem is that the output is always double
. I would like to have the answer to be an integer answer if the result is an integer, say, 2
instead of 2.0
.
Cases:
-
A= 2
andB= 2
(input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result =>4
-
A= 2.0
andB= 2.0
(input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result =>4.0
I looked it up and it wasn't much help. As such questions either deal with conversion or precision. Links to any similar/helping questions that I might have missed will work too. I know how to convert from float
to int
, but looking for optimum way to check if a number can be represented in int or not. And get result accordingly.
Thank you
答案1
得分: 1
你可以尝试使用%运算符来判断这两个双精度数是否产生了一个完美的除法,并像下面这样使用整数转换。
double num1 = 20.0;
double num2 = 5.0;
if (num1%num2 == 0) {
System.out.println((long) (num1/num2));
} else {
System.out.println(num1/num2);
}
英文:
You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below.
double num1 = 20.0;
double num2 = 5.0;
if (num1%num2 == 0) {
System.out.println((long) (num1/num2));
} else {
System.out.println(num1/num2);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论