【发布时间】:2020-08-22 21:24:30
【问题描述】:
问题:要显示此模式的 n 项的总和,例如 1+11+111+1111+11111..n 项
测试数据:
输入词条数:5。
预期输出:
1 + 11 + 111 + 1111 + 11111 总和是:12345
我正在尝试这种方式->
//To display the sum of series like 1+11+111+11111
#include <stdio.h>
int
main(void){
//Here i declared some variables for storing information
int number,iteration,value=1,j,summation=0;
//Message to user
printf("Input the number of terms : ");
//taking input from the user
scanf("%d",&number);
//this condition will work till the iteration reaches to the inputted number
for(iteration=1; iteration<=number; iteration++){
for(j=1; j<=iteration; j++){
//To display the series like 1 11 111 1111 11111
printf("%d",value);
if(j==1){
summation=summation+value;
}
else if(j==2){
summation=summation+value*10;
}
else if(j==3){
summation=summation+value*100;
}
else if(j==4){
summation=summation+value*1000;
}
else if(j==5){
summation=summation+value*10000;
}
}
printf(" ");
}
printf("\n");
//To display the summation
printf("The summation is : %d",summation);
return 0;}
现在我的问题是:这段代码不符合我的预期。它正在输入值 5。但是当我想输入 6 次时,我需要在我的代码中另外添加一个 else if 条件。每当我增加输入值时,我都需要执行此任务。
当输入值为 6 并且我需要添加并制作这样的条件时->
else if(j==6){
summation=summation+value*100000;
}
所以我认为,这不是正确解决问题的方法。每次我需要对输入的值做同样的事情。我怎么解决这个问题?。之后如何简化解决方案?我相信你们比我更专业。请与我分享你的知识。提前谢谢你。
【问题讨论】:
-
对于 n 个术语 @Yunnosch
-
也许尝试递归?注意整数类型的有限范围...
unsigned long long至少为 64 位,能够容纳高达18446744073709551615的值 -
将 2000 万个数字加起来,最多 2000 万位数,您需要使用的不仅仅是一个整数变量
-
@Bob__ 该字符串需要容纳约 4000 万个字符。这就是我所说的“不仅仅是一个变量”;)
-
@Ashifulislamprince 你有你正在解决的原始问题的链接吗?
标签: c