+ 1

switch vs if else statement

in my quest to learn c++ i found this problem: You work in a toy car workshop, and your job is to build toy cars from a collection of parts. Each toy car needs 4 wheels, 1 car body, and 2 figures of people to be placed inside. Given the total number of wheels, car bodies and figures available, how many complete toy cars can you make? Although it doesn't sound too complicated, i found myself in loop full of errors like case labels form a switch are not a constant expression or the if statement doesn't work. Another error is when i tried to use std::min from the algorithm library. Can you help mw with it and point out what i did wrong? Here's the code i tried to work with and with the minimum number of errors: #include <iostream> #include <algorithm> int cars(int w, int b, int f) //w for wheels, b for car bodies, f for figures { int build = 0; if (w < 4 || b < 1 || f < 2) //will check for the minimum requirements to build a car { std::cout << "Can't build a car! Please review your input"; } else { if (std::min(w, b, f) == w) { build = w / 4; return build; } else if (std::min(w, b, f) == b) { if (w < f) { b = w / 4; build = b; return build; } else { b = f / 2; build = b; return build; } } else if (std::min(w, b, f) == f) { build = f / 2; return build; } } } int main() { int wheels, bodies, figures; std::cout << "Input number of wheels: "; std::cin >> wheels; std::cout << "Input number of bodies: "; std::cin >> bodies; std::cout << "Input number of figure: "; std::cin >> figures; std::cout << cars(wheels, bodies, figures); return 0; }

19th Jul 2021, 5:37 AM
Thr3at
1 Answer
+ 3
The min() function is used with only two values. That is, in order to find the minimum value of three variables, you need: #include <iostream> using namespace std; cout << min(min(w,b),f);
19th Jul 2021, 9:24 AM
Solo
Solo - avatar