Concept

How can conditionals validate logarithm inputs and handle errors?

ComputerScienceOne / Life & Taxes

"The user could enter invalid values such as b = − 10 or x = − 2 . 54 (logarithms are undefined for non-positive values in any base). We want to ensure that b > 1 and x > 0. With conditionals, we can now do this. Once we have read in the input from the user we can make a check for good input using an if statement.\n\n1 if(x <= 0 || b <= 1) {\n\n2 printf(\"Error: bad input!\n\n\");\n\n3 exit(1);\n\n4 }\n\nThis code has something new: exit(1). The exit() function immediately terminates the program regardless of the rest of the code that it may remain. The argument passed to exit is an integer that represents an error code. The convention is that zero indicates “no error” while non-zero values indicate some error. This is a simple way of performing error handling: if the user provides bad input, we inform them and quit the program, forcing them to run it again and provide good input. By prematurely terminating the program we avoid any illegal operation that would give a bad result. Alternatively, we could have split the conditions into two statements and given more descriptive error messages. We use this design in the full program which can be found in Code Sample 16.2. The program also takes the input as command line arguments. Now that we have conditionals, we can actually check that the correct number of arguments was provided by the user and quit in the event that they don’t provide the correct number."

Related Ideas

How can conditionals validate logarithm inputs and handle errors? | ComputerScienceOne | Bifalgorithm | Bifalgorithm