我正在嘗試制作一個嵌套的 for 回圈,其中外回圈和內回圈進行一定數量的總迭代,但它們各自的迭代次數不同。相反,應該根據給定的比率和給定的總迭代次數計算每個回圈的迭代次數。我的函式將接受總的迭代次數, ( M) 和 a ratio。基于此,它應該計算外回圈應該迭代多少次,內回圈應該迭代多少次,使得總迭代次數等于M。
例如,給定ratio = 0.5and M = 225,每個回圈應該迭代相同的次數(因為比率是 50%),并且總迭代應該等于 225。在這種情況下,每個回圈應該進行15迭代:
for(int i = 0; i < 15; i ) {
for(int j = 0; j < 15; j ) {
...etc
在一些代碼的背景關系中:
//these will be given as function parameters, but for these purposes they are constant
int M = 225;
double ratio = 0.5;
int outerIterations = //some calculation
int innerIterations = //some other calculation
//the amount of iterations each loop has done
int totalIters = 0;
for(int i = 0; i < outerIterations; i ) {
for(int j = 0; j < innerIterations; j ) {
totalIters ;
//in here, something is done M times
}
}
在上面的例子中,totalIters應該等于200,outerIterations應該等于15,也innerIterations應該等于15。這個例子很簡單,因為兩個回圈之間只有 50/50(因為比率是0.5)。問題是我不知道如何從比率和總迭代中獲得我需要的 2 個值。
我努力了:
int innerIterations = (int)(M * ratio)
int outerIterations = (int)(M / innerIterations)
//This produces 2 numbers that will multiply to M, but doesn't maintain the correct ratio
除此之外,我不知道從哪里開始,因為這似乎是一個相當獨特的問題,而且我所做的 google/stackoverflow 搜索都沒有產生任何相關的東西。
總的來說,我要問的問題是我需要執行哪些計算才能獲得這兩個值(outerIterations和innerIterations),因此 for 回圈保持給定的比率和迭代M次數。
uj5u.com熱心網友回復:
首先,我們需要確定您的比率的含義。我將把它理解為外部迭代與總數(外部 內部)的比率。
outer/(outer inner) = ratio
outer = ratio(outer inner)
outer = ratio * outer ratio * inner
outer - ratio * outer = ratio * inner
outer(1 - ratio) = ratio * inner
outer = ratio/(1 - ratio) * inner
我們也知道外部和內部的乘積將是總迭代次數
outer * inner = total
ratio/(1 - ratio) * inner2 = total
inner2 = total(1 - ratio)/ratio
inner = √(total(1 - ratio)/ratio)
outer * inner = total
outer = total/inner
所以,這給我們留下了公式:
1) inner = √(total(1 - ratio)/ratio)
2) outer = total/inner
在你的情況下:
inner = √(225(1 - 0.5)/0.5) = √(225) = 15
outer = 225/15 = 15
當沒有整數解決方案時,您需要決定如何處理這些情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/495351.html
