方法1:
int sum_of_cubes(int n)
{
int sum = 0;
for (int i=1; i<=n; i++)
sum += i * i * i;
return sum;
}
void print_sum_of_cubes()
{
int n;
while (cin >> n && n > 0)
cout << sum_of_cubes(n);
}
方法2:
int sum_of_cubes(int n)
{
// 其值為 0 表示沒有存入答案
static int answer[10 + 1] = {};
// 如果已經計算過,就直接讀取表格的答案。
if (answer[n] != 0) return answer[n];
// 如果不曾計算過,就計算一遍,儲存答案。
int sum = 0;
for (int i=1; i<=n; i++)
sum += i * i * i;
return answer[n] = sum;
}
void print_sum_of_cubes()
{
int n;
while (cin >> n && n > 0)
cout << sum_of_cubes(n);
}
方法3:
void print_sum_of_cubes()
{
// 預先建立立方數表格
int cube[10 + 1];
for (int i=1; i<=10; i++)
cube[i] = i * i * i;
int n;
while (cin >> n && n > 0)
{
// 直接讀取表格的立方數
int sum = 0;
for (int i=1; i<=n; i++)
sum += cube[i];
cout << sum;
}
}
方法4:
int sum_of_cubes(int n)
{
int sum = 0;
for (int i=1; i<=n; i++)
sum += i * i * i;
return sum;
}
void print_sum_of_cubes()
{
// 預先計算所有答案
int answer[10 + 1];
for (int i=1; i<=10; i++)
answer[i] = sum_of_cubes(i);
// 直接讀取表格的答案
int n;
while (cin >> n && n > 0)
cout << answer[n];
}
方法5:
void print_sum_of_cubes()
{
// 預先計算答案,寫死在程式碼裡面。
int answer[10 + 1] =
{
0, 1, 9, 36, 100, 225,
441, 784, 1296, 2025, 3025
};
// 直接讀取表格的答案
int n;
while (cin >> n && n > 0)
cout << answer[n];
}