我认为解决方案很简单,并且可能与其他问题重复。对不起,如果这个答案会重复另一个。我无法找到解决方案,因为我不知道我在寻找什么。嗯,我有这个简单的函数来计算全部成本总和。如何简化此功能,例如在数学函数中。
public int getFullCosts ()
{
int initialCosts = 10;
int currentCount = 3;
int fullCosts = 0;
for (int i = 1; i <= currentCount; i++) {
fullCosts += i * initialCosts;
}
return fullCosts;
}
最佳答案
这个函数正在计算:
fullCosts = 1*initialCosts + 2*initialCosts + ... + currentCount*initialCosts
等于:
initialCosts * (1 + 2 + ... + currentCount)
the sum of the first n
natural numbers is given by (n * (n + 1))/2
initialCosts * ((currentCount + 1) * currentCount)/2
下面是我的做法:
public int sumOfFirstNInts(int n) {
return (n * (n+1)) / 2;
}
public int getFullCosts() {
int initialCosts = 10;
int currentCount = 3;
return initialCosts * sumOfFirstNInts(currentCount);
}
关于c# - 为我的计算寻找数学函数(算术级数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454659/