当前位置:网站首页>JS - for cycle case: Horse grain

JS - for cycle case: Horse grain

2022-06-13 08:22:00 tingkeaiii

One 、 subject

 One shipment to Malaysia 2 Stone grain , China Malaysia transportation 1 stone , Two little horses 1 stone , Use 100 A horse , shipment 100 Stone grain , How to allocate 

Two 、 Source code and result diagram

      for (var i = 0; i <= 50; i++) {  /* Malaysia i*/
        for (var j = 0; j <= 100; j++) { /* Zhongma j*/
          for (var k = 66; k >= 0; k--) { /* The pony k*/
            if ((parseInt(k / 2) + j + i * 2 == 100) && (i + j + k == 100)) {
              console.log(' Malaysia needs ' + i + ' horse ' + '\n' + ' China and Malaysia need ' + j + ' horse ' + '\n' + ' The pony needs ' + k + ' horse ');
            }
          }
        }
      }

3、 ... and 、 Solution steps and ideas

 ( One ) Ideas :

Use three layers for loop , Each cycle represents a horse , Use if Statement to filter out the conditions that match the number of horses , And meet the conditions of grain quantity , If it meets the requirements, it will be output .

( Two ) The problem solving steps :

1.        First of all, it is necessary to define the value range of each type of horse , For example, a big horse carries two bags of grain at a time , If the number of Damascus exceeds 50, The total transportation volume exceeds the standard ; Two ponies carry one bag , If the number of ponies is more than 67 Still small , No amount of Malaysia can carry all its grain , To determine i,j,k Value range of . Let's assume that Malaysia 0 only , Zhongma 0 only , The pony 66 As the first data , The pony k Decline .

      for (var i = 0; i <= 50; i++)
        for (var j = 0; j <= 100; j++) 
          for (var k = 66; k >= 0; k--) 

2.        Set in the innermost loop if Statement to filter conditions . The conditions are 2: The total amount of grain is 100, The number of horses adds up to 100, Both conditions are indispensable

(parseInt(k / 2) + j + i * 2 == 100) && (i + j + k == 100)

3.         Output that meets this condition j,i,k result , And concatenate strings to make the result clearer

 console.log(' Malaysia needs ' + i + ' horse ' + '\n' + ' China and Malaysia need ' + j + ' horse ' + '\n' + ' The pony needs ' + k + ' horse ');

Four 、 summary

         The topic is to clarify the thinking and organization before moving the handwritten code , Thinking is far more important than writing code . This is the purpose of this exercise . In the process of doing questions , Write if Forget to write the number of horses in the conditional statement =100 This is the condition , Make the result incomplete . After writing the code, you have to look at the title again ! See if there is any omission in the requirements .

原网站

版权声明
本文为[tingkeaiii]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270542515351.html