如果我想獲得與數字最接近的值,但該值也必須在名爲IsMultipleOf7
的bool上返回true,該值在7的倍數處返回true。獲取距離最近的值,在布爾上返回true
例如,我有一個int x = 523
。所以7的最接近倍數是525,所以我的布爾將返回真實525.
我怎樣才能得到這個數字?
如果我想獲得與數字最接近的值,但該值也必須在名爲IsMultipleOf7
的bool上返回true,該值在7的倍數處返回true。獲取距離最近的值,在布爾上返回true
例如,我有一個int x = 523
。所以7的最接近倍數是525,所以我的布爾將返回真實525.
我怎樣才能得到這個數字?
int x = 523;
while ((int)x/7!=(decimal)x/7){
x++;
}
return x;
如果x = 526,該怎麼辦?最近的仍然是525,但你的代碼將返回532。 – J0HN
有兩種方法我可以想到。首先是我評論的強力方法。如果您從號碼x
開始,請對其進行測試。如果有效,萬歲!如果不是,請嘗試向x添加一個並進行測試。然後從x中減去一個並進行測試。然後用兩個和三個同時進行測試。一旦你的測試返回true,你就找到了最接近的數字(一個)。這種方法是一個通用的方法,可以用於任何測試功能。
因爲我們知道您正在使用IsMultipleOf7
作爲測試,所以可以採用更智能的方法。想象一下,如果你的測試是IsMultipleOf999999999
,那就需要花費時間!如此多的數字可能需要在接近最近之前進行測試。相反,可以使用一些數學。首先,計算x模7(用於IsMultipleOf7
),用C(++)寫成x % 7
。這個值告訴你X距離LESS的最大倍數是多少。如果此值爲0,則x是7的倍數。如果值爲1,2或3,則x 減去該值是最接近的倍數。如果值爲4,5或6,則x 加上使得7的差值(7 - value
)是最接近的倍數。
一些僞代碼:
x = 523
value = x modulo 7
if(value == 0):
return x
if(value < 4): // that is, less than half of 7
return x - value
otherwise
return x + (7 - value)
int x = 523;
int result = ((x/7) + 1) * 7;
你可能需要一個更復雜的公式,如果您的號碼是7整除,並應保持相同的號碼。或者你可能已經簡化了你的問題了?
該函數將返回的7
最接近的數倍或數本身如果是7
public int GetClosestNumber(int number, out bool isMultipleOf7)
{
// if the number is a multiple of 7 isMultipleOf7 is set to true
isMultipleOf7 = number%7 == 0;
if (isMultipleOf7)
{
// if it's a multiple of 7 then the closest one is the number itself
return number;
}
// if it's not a multiple of 7 then try find the closest.
var lower = number - (number % 7);
var upper = (number + 7) - (number %7);
var diffL = Math.Abs(number - lower);
var diffU = Math.Abs(number - upper);
return diffL > diffU ? upper : lower;
}
的倍數,這裏有一個使用示例:
bool IsMultipleOf7;
// Following line will output: Closest multiple of 7 is: 525
Console.WriteLine("Closest multiple of 7 is: {0}",
GetClosestNumber(523, out IsMultipleOf7));
// Following line will output: The number itself is not a multiple of 7"
Console.WriteLine("The number itself is {0} a multiple of 7",
IsMultipleOf7 ? string.Empty: "not");
x=7*Math.Round(((float)x)/7.0)
^最簡單的解決方案就在那裏;)
不需要所有這些循環和東西。
除以7,如果小數小於0.5,則最接近的分母是floored,否則是ceiling。 Round()爲你做了這個,然後把你的新int乘以7來創建一個可以被7整除的數字(因爲它是一個int乘以7)。它將得到以下最接近的值或以下。根本不需要布爾。確保你在x上浮動,這樣它可以被7除以不會導致整數邏輯地板。
我能想到的最明顯的就是測試數字x,然後測試下面和上面的數字,然後測試下面的數字和上面的數字等,等等,並繼續以這種方式:一個蠻力。 – bimmo
我更喜歡是否有另一種方式來做到這一點,而不是蠻力,因爲我的真實數字是巨大的,而蠻力的確會減慢我製作的節目的速度。如果IEnumerable中存在類似的東西,它會非常棒。在IEnumerable中,它可以跳過所有在bool中返回false的東西。 – gcnew
它什麼時候會返回false?要求不清楚。 –