为什么我的“ for”循环仅运行两次?

时间:2019-11-22 16:54:23

标签: c for-loop while-loop breakpoints

我正在做的任务是输入5个具有5位数字的随机数,以对其进行压缩并求和。那么我们如何压缩它们呢?我们摆脱了第二和第四位数字。例如12345到10305。

这是我的代码。

int main()
{
    int n=5,i,j,number5,num1,num3,numb5,sum;
    for(i=0;i<n;i++) // 5 times we read next for loop right ?
        for(j=0;j<i;j++){ // this loop read 5 times 5 digits number 
            scanf("%d",&number5); // scanf 1 number
            while(number5){ // while number isn't 0 ( false )
                num1=number5/10000;
                num1*=10000;
                num3=(number5%10000)%1000/100;
                num3*=100;
                numb5=(number5%10000)%1000%100%10; 
                numb5*=1;// mathematic operations to get to 1st third and 5th number
                number5=0; // set the number5 to 0 so we can go out of while right ?
            }
            sum=num1+num3+numb5; // we get the sum of the first 5 digits and we get it on the second when j++ right ?

        }
         printf("%d",sum);// on the end of all five number with 5 digits we get the sum right ?
}

那我的for循环为什么只运行两次而不是五次?

4 个答案:

答案 0 :(得分:0)

您真的想得太多了。

input()

See it in action here

答案 1 :(得分:0)

只需在第二个循环中将j<i移至j<5,您就可以得到五个{5}压缩数字的总和,n次。

答案 2 :(得分:0)

我在摘要中提到的错误是唯一的问题,其他一切都很好。 请参阅附件。

// only two loops are required    
for(int i=0;i<5;i++){
    scanf("%d",&number5);
    sum=0;
    while(number5){ 
            num1=number5/10000;
            num1*=100;//it should be 100 isntead of 10000
            num3=(number5%10000)%1000/100;
            num3*=10;// it should be 10 istead of 100
            numb5=(number5%10000)%1000%100%10; 
            numb5*=1;
            number5=0; 
        }
    sum=num1+num3+numb5; 
    printf("%d\n",sum);
}

答案 3 :(得分:0)

#include <stdio.h>
    #include <stdlib.h>

    int main()
{
    int n=5,i,j,number5,num1,num3,numb5;
    int sum=0;


    for(i=0;i<n;i++) {
       scanf("%d",&number5);//runs 5 times to get 5 inputs

       sum+=(number5/10000)*10000; // take the value of first position
       sum+=((number5/100)%10)*100; // take the value of third position
       sum+=(number5%10);// take the value of fifth position

        }
         printf("%d",sum);
}