为什么我的 "for" 只循环 运行 两次?

Why does my "for" loop run only two times?

我做的任务是输入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 循环 运行 只循环两次而不是五次?

你真是想多了。

int n;

for(int i=0; i < 5; ++i)
{
    // read first number eg 12345
    scanf("%d",&n);
    int d1 = n % 10;    // ones place = 5
    n /= 100;           // n becomes 123
    int d100 = n % 10;  // hundreds place = 3
    n /= 100;           // n becomes 1
    int d10000 = n % 10;    // ten thousands place = 1

    int smallSum = 100*d10000 + 10*d100 + d1;
    // prints 135 
    printf("sum version 1 = %d\n", smallSum); 

    int bigSum = 10000*d10000 + 100*d100 + d1;
    // prints 10305
    printf("sum version 2 = %d\n",bigSum);     
}

See it in action here

只需在第二个循环中将j<i设为j<5,就可以得到五个5位压缩数字的总和n次。

我在代码片段中提到的错误是唯一的问题,其余一切都很好。 请参阅附件片段。

// 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);
}
#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);
}