You are here:

C++/computing the area of a triangle


hello, i have an assignment due on computing the are of a triangle using 3 teacher really is no help and a tough grader...the first function needs to prompt the user for an edge and returns it as a double as well as not allowing the the user to enter a negative number...i am really lost and do not know where to begin..

Hello Christopher.

The toughest part of this sort of assignment is handling the user's input. You have to handle anything the user inputs, not matter how incorrect it is. One way to do input is to send cin directly to a double value, like this:

double value;
cin >> value;

but I find it more reliable to use getline. The getline inputs an entire line into a string, then you can call the atof function to parse the string into a double. I will provide you with an input function, and you can finish the assignment.

As you probably know, you need a base and a height to calculate the area. I will use one input function for both. The getValue function prompts the user for a value until the user enters something that can be parsed as a double value that is greater than zero. If the user enters many "words" on a line, only the first word is looked at by atof. The getValue function uses a name parameter to create the prompt. The name parameter makes the function flexible enough to be used for both base and height inputs.

#include <iostream>
#include <string>

using namespace std;

double getValue(const char* name)
   double value;
       cout << "Input the " << name << ": ";
       string input;
       // getline reads in an entire line from the user into a string
       getline(cin, input);
       // atof takes the first word from the line,
       // and tries to parse it as a floating point value.
       value = atof(input.c_str());
       if (value <= 0)
         cout << "The " << name << " must be greater than 0\n";
   } while(value <= 0);
   return value;

int main(void)
   double base = getValue("base");
   double height = getValue("height");

   // Now you calculate the area, and print it out.


All Answers

Answers by Expert:

Ask Experts




No longer taking questions.


No longer taking questions.

No longer taking questions.

©2017 All rights reserved.