+ 3

Why here we have: int accelerate(){speed+= acceleration; return speed;} ?

https://drive.google.com/file/d/1Abqudh3IaH03ur3TjUcBIJQXymbInFoH/view?usp=drivesdk

3rd Mar 2019, 7:09 AM
Cheshirlvova
Cheshirlvova - avatar
3 Answers
+ 3
In the quiz it asked to return the speed after accelerating. So that code is to do that thing. speed += acceleration will increase the value of speed by the value of acceleration and then it will return the speed.
3rd Mar 2019, 7:14 AM
Seniru
Seniru - avatar
+ 2
Because the type of speed is int, and there we must increment this variable by acceleration;
3rd Mar 2019, 7:15 AM
Cheshirlvova
Cheshirlvova - avatar
+ 2
The function looks unnecessarily complicated to me. If you want to increase the variable speed, you don't need a return value: void accelerate(int acceleration) { speed += acceleration; } If you want the function to return a value, there is no need to increase "speed" from within the function: int accelerate(int acceleration) { return speed + acceleration; } As it is, the function int accelerate(){ speed += acceleration; return speed; } looks like it has two purposes: increase "speed" and return a value that indicates if the object is moving. If the initial speed is 0 and it is increased by 0 (or speed is n and it is increased by -n (aka slowed down)), it will return 0 (as in: object stands still). Any return value other than 0 would imply that the object is moving.
3rd Mar 2019, 9:14 AM
Anna
Anna - avatar