-
March 22nd, 2011, 12:17 AM
#1
C++ Simple Math Program
Hi guys!
Making a simple math program calculating the quadratic formula so that I can get practice using multiple methods and basic in/out prompts. I wanted to add a simple check to make sure that what is being inputed for "a", "b", or "c" isn't a character that cannot be used in a calculation. Not sure about how to work the exception for it. Any advice? This is what I have so far..
[code] #include <iostream>
#include <math.h>
#include <stdio.h>
#include <cmath>
#include <string>
using namespace std;
//Discriminate Method :: Formula (b^2 - 4ac)
float discriminate(float a, float b, float c)
{
float discrim;
try
{
discrim = (b*b) - (4 * a * c);
}
catch(exception& e)
{
cout << "error" << endl;
}
return discrim;
}
float quadratic(float a, float b, float c)
{
float discrim = discriminate(a,b,c);
if (discrim < 0)
{
cout << "Discriminate is imaginary" << endl;
return 0;
}
else
{
float quad = sqrt(discrim);
return quad;
}
} //End of Quadratic Method
int main()
{
//Variable Declaration
float a, b, c;
//Welcome Message
cout << "Welcome to Josh's Quadratic Formula C++ Program" << endl;
cout << "================================================" << endl;
cout << "" << endl;
cout << "Input A: " << endl;
cin >> a;
cout << "Input B: " << endl;
cin >> b;
cout << "Input C: " << endl;
cin >> c;
float answer = quadratic(a,b,c);
if (answer == 0)
{
cout << "Imaginary Number: Cannot Calculate" << endl;
}
else
{
cout << "The answer: +/- " << answer << endl;
}
return 0;
}
[code]
-
March 22nd, 2011, 04:12 AM
#2
Re: C++ Simple Math Program
See http://www.parashift.com/c++-faq-lit....html#faq-15.2 for full explanation.
If something that is not a float is entered for a, then b and c will not actually be read. Depending on how you want to handle it, you could check after each input or after several inputs.
PS closing code tag is [/code], not [code].
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
-
March 22nd, 2011, 07:02 AM
#3
Re: C++ Simple Math Program
haha oops on the [\code] ;p That's what I meant to put!
Thanks for that article! Filled with great information. I will be sure to give those things a try when I get the chance later today!
-
March 23rd, 2011, 10:04 PM
#4
Re: C++ Simple Math Program
Don't forget the -b plus or minus, and the (2a):
quad = (-b +/- sqrt(discrim))/(2a);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|