### a simple algorithm

below is a part of my code but I am looking for a way to make it shorter. ?

 ``12345678910111213`` ``````int box1=0; int box2=0; int box3=0; int box4=0; int box5=0; std::cin >> number; if ( number > 2.0 && number < 2.5 ) box1 += 1.; if ( number > 2.5 && number < 3.0 ) box2 += 1.; if ( number > 3.0 && number < 3.5 ) box3 += 1.; if ( number > 3.5 && number < 4.0 ) box4 += 1.; if ( number > 4.0 && number < 4.5 ) box5 += 1.;``````

thanks.
 ``123456789`` ``````int box1=0, box2=0, box3=0, box4=0, box5=0; std::cin >> number; if ( number > 2.0 && number < 2.5 ) box1 += 1.; if ( number > 2.5 && number < 3.0 ) box2 += 1.; if ( number > 3.0 && number < 3.5 ) box3 += 1.; if ( number > 3.5 && number < 4.0 ) box4 += 1.; if ( number > 4.0 && number < 4.5 ) box5 += 1.;``````
Take a look at arrays.
Develop an equation to obtain the box by passing the number.
This is what I managed. It was fun

 ``123456789101112131415161718`` ``````#include int boxes[5] = {0, 0, 0, 0 ,0}; int i; float number; float step = 0.5; float lowest = 2.0; float highest = 4.5; std::cin >> number; if(number > lowest && number < highest) // Checks if the input is out of range { if(std::fmod(number, step) != 0) // Checks if the remainder of number/step is different from 0. This is to exclude values like 2.5, 3, 3.5, etc { i = int((number - lowest) / step); boxes[i] += 1; } }``````

I must say that I didn't test the code, so I can't guarantee for it
Topic archived. No new replies allowed.