簡體   English   中英

為什么我的“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);     
}

在這里查看它的實際應用

只需在第二個循環中將j<i設為j<5 ,您就可以得到五個 5 位壓縮數字的總和n次。

我在片段中提到的錯誤是唯一的問題 rest 一切都很好。 請參閱附加的片段。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM