Quiz Week 3 – Square/Cube Root

--Originally published at Franco TC1017

This program calculates the square root and cube root of a number given by the user. I included #include <math.h> so I could use sqrt() and cbrt(). Although it is recommended to use #include <cmath> instead. The code recognizes if the user inserts a negative number, therefore it tells the user that the square root is not calculable.

#include <iostream>
#include <math.h>

double square_root(double x){
double square_root = sqrt(x);
return square_root;
}

double cube_root(double x){
double cube_root = cbrt(x);
return cube_root;
}

int main() {

double x;

std::cout << “SQUARE ROOT AND CUBE ROOT CALCULATOR” << ‘\n’;
std::cout << “Insert a number” << ‘\n’;
std::cin >> x;

if (x < 0) {
std::cout << “Square root: ERROR: number cannot be negative.” << ‘\n’;
std::cout << “Cube root: “<< cube_root(x) << ‘\n’;
} else {
std::cout << “Square root: “<< square_root(x) << ‘\n’;
std::cout << “Cube root: ” << cube_root(x) << ‘\n’;
}

return 0;
}

 

quiz-3-codequiz-3-terminal