你能解决我的问题并简化我的代码吗?我找不到针对这个特定问题的干净解决方案

标签 c

问题:显示 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;
             }

所以我认为,这不是正确解决问题的方式。每次我都需要对输入的值做同样的事情。我怎么解决这个问题?。之后我该如何简化解决方案?我相信你们比我更专业。请与我分享您的知识。预先感谢您。

最佳答案

将输入数字传递给此函数。

    int findSum(int n) 
    { 
        int sum=0, cnt= 1; 
        for (int i = 1; i <= n; i++) { 
            sum += cnt; 
            cnt = (cnt * 10) + 1; 
        } 
      
        return sum; 
    } 

关于你能解决我的问题并简化我的代码吗?我找不到针对这个特定问题的干净解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63483300/

相关文章:

c - Fgets 被忽略且程序仅读取 2 个输入数据(链表)

c - printf 数组的整个单元

c - 使用 DWARF 全局变量的位置(和重定位)

c - C 上的 libmongoc-1.0.pc/MongoDB 出现问题

c - qsort比较功能不起作用

C:使用位运算将十进制转换为十六进制

c - 如何在C中实现动态数组?

c - 更新在c中使用#define定义的变量的值

C:启动旨在识别字符串模式的程序时遇到问题

c - C 编程中的错误 "void value not ignored as it ought to be"