gpt4 book ai didi

c - 使用三个数字查找整数的总数组合

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:48:28 26 4
gpt4 key购买 nike

对于给定的整数 n,我需要打印所有长度为 3 且总和为 n 的列表。列表的成员必须是非负整数。打印所有这些列表后,它必须打印找到的列表数。

例如,如果n=2:

  • 1+0+1 = 2
  • 1+1+0 = 2
  • 0+1+1 = 2
  • 2+0+0 = 2
  • 0+0+2 = 2
  • 0+2+0 = 2

这是我为长度为 2 而不是长度为 3 的列表所做的程序:

#include <stdio.h>
int main (void)
{
int total;
int c1=0;
int c2=0;
int c3=0;
int count;

printf("Welcome friends and mainly enemies to the thingy. Only postive intergers!!!\n That's right just enter a number here:");
scanf ("%d",&total);
printf ("\n\n\nWhy pick %d? Here is the list if combinations anyway,",total);

for (count=0;count<=total;count++)
{
printf ("\n");
for (c1=count;c1==count;c1--)
{
printf("%d ",c1);

}
for (c2=total-count;c2<=total-count;c2++)
{
printf("%d",c2);

}

}
printf ("\n\nThere are %d number combinations that total %d",count,total);

}

目标是将其从长度为 2 的列表扩展到长度为 3 的列表。

附加信息:我只能使用另一个变量 c3。

最佳答案

希望对您有所帮助:

int c3 = 0;
for (int c1 = 0; c1 <= total; c1++) {
for (int c2 = total - c1; c2 >= 0; c2--){
printf("%d %d %d \n", c1, c2, total - c1 - c2);
c3++;
}

}

printf("there are %d ways to sum to %d", c3, total);

关于c - 使用三个数字查找整数的总数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8871180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com