[英]Creating a Series of four Numbers
在一次采訪中,他們要求我編寫一個Java程序。 問題是這樣的,
有一個開始和結束編號。將開始和結束之間的數字除以4個相等的部分,並打印其10s次方。 如果start = 110,end = 1234的示例
結果是得到
300
600
900
1000
我已經完成了將其分為4部分的代碼,但是我無法舍入到10s的功率。 我的代碼是
double start = 110;
double end = 1234;
double n = 4;
double difference = (end - start) / n;
double value = start;
while (value < end)
{
value += difference;
System.out.println(value);
}
ouput/
391.0 672.0 953.0 1234.0如何舍入我的值?
對於每個value
,請使用以10為底的對數獲取其10的冪。 例如:
int log_10 = (int) Math.log10(value); // For 391.0, result is 2
然后,它很容易:
long basePower = (long) Math.pow(10, log_10); // Yoy get 100
int result = ((int) (value/basePower)) * basePower; // You get 300
其他值相同:
1234.0 ==>
log_10 = 3;
basePower = 1000;
(int) (1234.0/1000) = 1 ==> result = 1*1000 = 1000;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.