可唔可以講解下呢個program?

2012-10-10 8:20 pm
#include <stdio.h>
#define N 7
int main(void)
{
int cnt = 0, i, j, k;
for (i = 0; i <= N; ++i)
for (j = 0; j <= N; ++j)
for (k = 0; k <= N; ++k)
if (i + j + k == N) {
++cnt;
printf("%3d%3d%3d\n", i, j, k);
}
printf("\nCount: %d\n", cnt);
return (0);
}

回答 (3)

2012-10-11 6:02 am
✔ 最佳答案
用三個數ijk,由零數到N,數一數三數總和等於N出現幾次,及每次打印出該組合。
int cnt = 0, i, j, k; //定義 i,j,k為integer
for (i = 0; i <= N; ++i) // for loop,每個數都由0數到n
for (j = 0; j <= N; ++j)
for (k = 0; k <= N; ++k)
if (i + j + k == N) { // 檢測總和是否等於 n
++cnt; // 如果是,cnt加一
printf("%3d%3d%3d\n", i, j, k); // 印出該組合
}
2012-10-11 8:52 am
請問當k=8,要跳出第三個for loop, j 變左1, 再入多次第三個for loop個陣, k係咪由0開始?
仲有, 如果++i,++j,++k 變哂i++,j++,k++ 係咪冇分別?
THX OPZ
2012-10-11 6:57 am
#define N 7
--> put 7 into variable "N"

Result of running
0 0 7
0 1 6
0 2 5
0 3 4
.....
6 0 1
6 1 0
7 0 0
Count : 36
就是三個數加埋要=N (7)
一共有36個可能

2012-10-10 22:58:46 補充:
#include
#define N 7
int main(void)
{
int cnt = 0, i, j, k;
for (i = 0; i <= N; ++i)
{
for (j = 0; j <= N; ++j)
{
for (k = 0; k <= N; ++k)
{
if (i + j + k == N)
{
++cnt;

2012-10-10 22:59:11 補充:
printf("%3d%3d%3d\n", i, j, k);
}
}
}
}

printf("\nCount: %d\n", cnt);
return (0);
}

2012-10-10 23:00:35 補充:
每次由最右面的數(K)加起, +1, 直到 三個數的和是7


收錄日期: 2021-04-26 11:33:49
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20121010000051KK00136

檢視 Wayback Machine 備份