Bifalgorithm post · Computer science one · Life & Taxes

How can conditionals validate logarithm inputs and handle errors?

How can conditionals validate logarithm inputs and handle errors? (Computer science one · Life & Taxes) — "The user could enter invalid values such as b = − 10…

Ideas in this flowchart

  • Validating input and handling errors in C
  • The user may enter invalid values, such as b = −10 or x = −2.54.
  • Logarithms require b > 1 and x > 0.
  • Conditionals can be used to check whether the input is valid.
  • After reading the input, an if statement checks for bad input.
  • The condition is x <= 0 || b <= 1.
  • If the condition is true, the program prints an error message.
  • exit(1) immediately terminates the program.
  • The integer passed to exit represents an error code.
  • Zero conventionally indicates no error, while non-zero values indicate an error.
  • Terminating early prevents illegal operations and forces the user to provide valid input again.
  • The conditions could instead be split into separate statements with more descriptive error messages.
  • Command line arguments can also be checked for the correct number of inputs.
  • The program can quit when the required number of arguments is not provided.
Feed/

How can conditionals validate logarithm inputs and handle errors?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.