gpt4 book ai didi

c - 我想仅使用一个 for 循环同时打印算术级数和几何级数,但我只能打印一个

转载 作者:行者123 更新时间:2023-11-30 20:29:27 25 4
gpt4 key购买 nike

int main()
{
char choice;
do
{
int num, ratio,iter,firstno = 0;
printf("enter the no of times\n");
scanf("%d",&num);
printf("enter the first num\n");
scanf("%d",&firstno);
printf("enter the ratio\n");
scanf("%d",&ratio);
int ap = 0, gp = 1;

for (iter = 1; iter <= num; iter++)
{
switch (iter)
{
case 1:
printf("AP : %d ",firstno);
break;
default:
ap = firstno + ratio;
printf("%d ", ap);
firstno = ap;
break;
}

}
printf("\n");

printf("do you want to continue(y/n):\n");
scanf(" %c", &choice);
} while(choice == 'y');
return 0;
}

如何仅使用一个 for 循环打印两个序列?我在 for 循环中使用了 switch case,但只能打印算术级数。谁能帮我吗? 输入:= 5 从2开始 共同差异3 (以上所有可能会有所不同,其用户选择预期输出:美联社:2 5 8 11 14普通话:2 6 18 54 162

最佳答案

您可以创建一个表格来使用单个循环显示 AP 和 GP

这是代码:

int main()
{
char choice;
do {
int num, ratio,iter,firstno = 0;
printf("enter the no of times\n");
scanf("%d",&num);
printf("enter the first num\n");
scanf("%d",&firstno);
printf("enter the ratio\n");
scanf("%d",&ratio);
int ap = firstno, gp = firstno;

printf("--------------------\n");
printf("| n | ap | gp |\n");
printf("--------------------\n");


for (iter = 1; iter <= num; iter++) {
printf("|%3d |%5d |%5d |\n", iter, ap, gp);
ap = ap + ratio;
gp = gp * ratio;
}

printf("--------------------\n");

printf("\n");

printf("do you want to continue(y/n):\n");
scanf(" %c", &choice);
} while(choice == 'y');
return 0;
}

输出:

--------------------
| n | ap | gp |
--------------------
| 1 | 1 | 1 |
| 2 | 3 | 2 |
| 3 | 5 | 4 |
| 4 | 7 | 8 |
| 5 | 9 | 16 |
| 6 | 11 | 32 |
--------------------

关于c - 我想仅使用一个 for 循环同时打印算术级数和几何级数,但我只能打印一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975229/

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