-
Write a main function that prompts the user to enter a positive
integer. If the integer is negative an error message should be printed,
otherwise print whether the number is odd or even (hint: if there is no
remainder when divided by two, the number is even, use the modulus operator
%). Sample output is shown below.
prompt> checkint
enter positive int: -3
-3 isn't positive, sorry
prompt> enter positive int: 15
15 is odd
prompt> enter positive int: 24
24 is even
-
The program below is Program 4.5, monthdays.cpp in the book.
#include <iostream>
#include <string>
using namespace std;
// illustrates cascaded if/else statements
int main()
{
string month;
int days = 31; // default value of 31 days/month
cout << "enter a month (lowercase letters): ";
cin >> month;
if ("september" == month)
{ days = 30;
}
else if ("april" == month)
{ days = 30;
}
else if ("june" == month)
{ days = 30;
}
else if ("november" == month)
{ days = 30;
}
else if ("february" == month)
{ days = 28;
}
cout << month << " has " << days << " days" << endl;
return 0;
}
Modify the sequence of cascaded if/else statements so that there are two
if statements, one for February and one that uses the OR operator
||. Hint, here are statements that checks if the month is january or february:
string month;
cout << "enter month: ";
cin >> month;
if ( ("january" == month) || ("february" == month))
{ cout << "you were born in the first two months" << endl;
}
else
{ cout << "you cannot be an aquarius" << endl;
}
-
(see pause/reflect 4.14) Write the function TriangleArea whose header
is given below. It returns the area of a triangle given three sides of
the triangle using the formula
area = sqrt(s * (s - a) * (s - b) * (s - c) );
where a, b, and c are the sides of the triangle and s is is the semi-perimeter,
or half the perimeter of the triangle.
double TriangleArea(double a, double b, double c)
// pre: a, b, c, are lengths of sides of a triangle
// post: returns the area of the triangle whose sides are a,b,c
{
// write code here
}
-
(see Exercise 4.7) Write a function (not main, just a function)
that returns the surface area of a person. The surface area is given by
the formula:
surface area = 7.184-3 * weight0.452 * heigh0.725
where weight is in kilograms and height is in centimeters. Here's a main
that calls the function, you must write the function:
int main()
{
double height,weight;
cout << "enter weight in kilos: ";
cin >> weight;
cout << "enter height in cm: ";
cin >> height;
double area = SurfaceArea(weight,height);
cout << "Your surface area is: " << area << endl;
return 0;
}
-
(see exercise 4.2) Write a function that converts an integer in the range
1 to 10 to a roman numeral. The function should return a string so that
IntToRoman(4) returns the string "IV" and IntToRoman(8)
returns the string "VIII"
string IntToRoman(int num)
// precondition: 1 <= num <= 10
// postcondition: returns Roman equivalent of num