Lab1 Ex2

You cannot submit for this problem because the homework's deadline is due.

Ex2. Operations on numbers (23 marks)

Put code for all the sub-questions in one file called ex2.m in order. You can use spaces to separate the sub-questions in your source code to enhance readability. This also applies to Ex3 and Ex4.

Ex2_1. Basic geometry (5 marks)

Get a radius \(r\) from user input, and print the surface area and the volume (on separate lines) of a ball with radius \(r\). In the case that \(r<0\), print Invalid input.

Recall how to use control statements covered in the lectures.

Sample Test Cases

Input:

3.2

Output:

  128.6796

  137.2583

Input:

-5

Output:

Invalid input

Ex2_2. Sum of digits (10 marks)

Get a natural number \(n\in \N \cap\[0,1000)\) from user input, and print the sum of all its digits. Print Invalid input if the number is outside the range or not an integer. The input will always be numbers.

Hint 1: Consider how you perform number base conversion, and search the MATLAB documentation for floor() and mod().

Hint 2: In MATLAB, the data type of input() will be double by default (check this using isa()!). A number is an integer if conversion to the integer data type does not alter its value.

Sample Test Cases

Input:

233

Output:

     8

Input:

12.34

Output:

Invalid input

Ex2_3. Quadratic equation solver (8 marks)

Get three real numbers \(a\), \(b\), and \(c\) from user input as a vector of length 3, and solve the equation \(a x^2 + b x + c = 0, a\neq 0\). Print its two solutions on separate lines.

In the case of two real roots, print the smaller one first. In the case of two complex roots, print the one with the smaller imaginary part first. In the case of two equal roots, print it twice.

Hint: Try sqrt(-1). Also, consider the case when \(a < 0\), and how this will influence which root is smaller compared to \(a > 0\).

Sample Test Case

Input:

[1 2 3]

Output:

  -1.0000 - 1.4142i

  -1.0000 + 1.4142i

Lab1 Exercises

Not Claimed
Status
Finished
Problems
5
Open Since
2022-05-19 18:15
DDL
2022-05-21 00:00
Extension
24.0 hour(s)