当前位置:网站首页>C language simple exercise No.17, about the combination of for and while loops

C language simple exercise No.17, about the combination of for and while loops

2022-06-11 22:54:00 Sky • Shang

Topic link :

Contains figures 9 Number of numbers _ Niuke Tiba _ Cattle from (nowcoder.com)

matters needing attention

1. First look at the requirements of the topic , Yes. Find that these numbers contain 9 How many figures are there in total , Instead of asking you how many there are 9

2. Be careful break Use

Question answer

#include <stdio.h>
int main ()
{
    int i = 0;
    int count = 0;
    for (i = 1;i < 2020;i++)
    {
        int m = i;// You can't use it directly here i Value , Because it will change , Make it next 
                  // The cycle of cannot reach i The expected value 
        
        while (m) // Here we should think of using while loop 
        {
            if (m % 10 == 9)
            {
                count++;
                break;// there break Must add , Because 
            }
            else
            {
                ;
            }
            m /= 10;// The function of this expression is to modify m Value , Make it work while loop 
                    // Judgment condition 
        }       
    }
    printf("%d\n",count);
    return 0;
}

Some comments about the code :

// here Can't be used directly i Value , Because it will make i The value of is modified directly , Make it next i The cycle of cannot reach i The expected value
        
while(m)  Here we should think of using while loop
     
 break;// there break Must add , Because
            
 m /= 10;// The purpose of this expression is In the revision m Value , Make it work while loop
                    // Judgment condition
        

原网站

版权声明
本文为[Sky • Shang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011630319622.html