仅打印总和为10的3位数字的数组 [英] Print only those arrays with 3 digits whose sum is 10 - C program
本文介绍了仅打印总和为10的3位数字的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输出:
1 2 3 4
1 2 7
1 3 6
1 4 5
1 9
2 3 5
2 8
3 7
4 6
10
预期输出:
1 2 7
1 3 6
1 4 5
2 3 5
I只希望总和为10且也只有3位的那几对数字,即应该显示总和为10的3对不同的数字,其余所有对都跳过或不显示。
I want only those pairs of digits whose sum is 10 and also has only 3 digits i.e, the pair of 3 distinct digits whose sum is 10 should be displayed, rest all other pairs get skip or not displayed.
下面是我为解决此问题而编写的完整源代码。
Below is my full source code which I have written for this problem.
#include <stdio.h>
#include <stdlib.h>
void partition(int part) {
int *parts, *ptr, i, idx = 0, tot = 0, cur = 1, max = 1;
while ((max * (max + 1)) / 2 <= part)
max++;`
ptr = parts = malloc(sizeof(int) * max);
for (;;) {
if ((tot += *ptr++ = cur++) < part)
continue;
if (tot == part) {
for (i = 0; i < ptr-parts; i++) {
printf("%d ", parts[i]);
}
printf("\n");
}
do {
if (ptr == parts) {
free(parts);
return;
}
tot -= cur = *--ptr;
} while (++cur + tot > part);
}
}
int main(int argc, char*argv[]) {
int n;
scanf("%d", &n);
partition(n);
return 0;
}
推荐答案
您的代码似乎太复杂了。这是一个简单的解决方案:
Your code seems way too complicated. Here is a simple solution:
#include <stdio.h>
#define SUM 10
int main(void) {
for(int a = 1; a < SUM; a++) {
for(int b = a + 1; b < SUM; b++) {
for(int c = b + 1; c < SUM; c++) {
if(a + b + c == SUM) {
printf("%d %d %d\n", a, b, c);
}
}
}
}
}
程序输出:
1 2 7
1 3 6
1 4 5
2 3 5
这可能更有效,但是它是一种简单的形式。
This could be more efficient but it is a simple form.
这篇关于仅打印总和为10的3位数字的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文