检查整数是否太大 [英] Check if Integer is too great
问题描述
我正在研究交易系统,用户正在设定交易所的价格和金额。
I am working on an exchange system and the user is setting the price and amount for an exchange.
我想确保交易所不超过整数最大值,但我遇到了问题。
I want to make sure that the exchange is no greater than the Integer maximum value, but I am running into a problem.
当交换金额达到9或更多时,即使我有一个检查以确保数字不大于最大值,它不起作用。我做了一些调试,当设置金额为9而价格为2,147,483,646(比最大数量少1)时,打印出来:
When the amount of the exchange is put to 9 or more, even though I have a check to make sure the number is no greater than the maximum value, it does not work. I have done some debugging and when setting the amount to 9 while the price is 2,147,483,646 (1 less than the max number), it prints out this:
2,147,483,630 - 9
2,147,483,630 - 9
这是我的调试代码,我应该添加什么来确保不会发生这种情况?
This is my debugging code, what should I add to it to make sure that this does not happen?
public void setPrimaryAmount(int primaryAmount) {
int price = primaryAmount * this.price;
System.out.println(Misc.format(this.price * primaryAmount) + " - " + primaryAmount);
if (price > Integer.MAX_VALUE ||
price == Integer.MAX_VALUE ||
price >= Integer.MAX_VALUE ||
price < 0 || price <= 0 ||
price++ == Integer.MAX_VALUE) {
System.out.println("Attempted to set a bad amount.");
return;
}
this.primaryAmount = primaryAmount;
}
尝试设置不良金额打印出来,直到您输入金额> = 9。
"Attempted to set a bad amount" prints out until you enter an amount >= 9.
推荐答案
您无法在int中存储值,然后检查到看看它对于int来说是否太大了。把它存放在一个很长的位置。
You can't store a value in an int, and then check to see whether it's too big for an int. Store it in a long instead.
long price = (long)primaryAmount * (long)this.price;
这篇关于检查整数是否太大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!