-
September 20th, 2009, 03:29 AM
#1
need help with c++ program
I need some help with a c++ program for my class, i can't figure out whats going on.
Input: from the user
Output: standard output AND file named "program3.txt"
Write a program that will calculate both roots of a quadratic equation. The program should ask the user to input a, b, and c and then write both roots to standard output (the screen) and a file named "program3.txt".
Your program should print the roots ordered from least to greatest.
If the quadratic equation has a negative discriminant your program should output "NO REAL ROOTS".
If the two roots are the same only report one root.
ax2 + bx + c = 0
Formula
Code:
Sample Input Sample Output
1, -3, -10 -2, 5
3, 6, 3 -1
2, -2, -12 -2, 3
3, -2, 20 NO REAL ROOTS
Here is so far what ive got
Code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, b, c, d;
double root1, root2, temp;
//output
cout << "enter a, b, c";
cin >> a >> b >> c;
//process
d = pow(b,2) - 4 * a * c;
if(d >= 0)
{
root1 = (-b + sqrt(d))/(2 * a);
}
if(d > 0)
{
root2 = (-b + sqrt(d))/(2*a);
}
if(root1 > root2)
{
temp = root1;
root1 = root2;
root2 = temp;
}
// output
if(d >= 0)
{
cout << root1 << " ";
}
if(d > 0)
{
cout << root2 << " " <<endl;
}
if(d < 0)
{
cout <<"No Real Roots" << " ";
}
cin.get();
cin.get();
return 0;
}
Can someone help me out with the sample output. i get the 2nd integer, but i dont get the first.
-
September 20th, 2009, 05:32 AM
#2
Re: need help with c++ program
Originally Posted by froxy
I need some help with a c++ program for my class, i can't figure out whats going on.
Code:
Sample Input Sample Output
1, -3, -10 -2, 5
3, 6, 3 -1
2, -2, -12 -2, 3
3, -2, 20 NO REAL ROOTS
Here is so far what ive got
Code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, b, c, d;
double root1, root2, temp;
//output
cout << "enter a, b, c";
cin >> a >> b >> c;
//process
d = pow(b,2) - 4 * a * c;
if(d >= 0)
{
root1 = (-b + sqrt(d))/(2 * a);
}
if(d > 0)
{
root2 = (-b + sqrt(d))/(2*a);
}
if(root1 > root2)
{
temp = root1;
root1 = root2;
root2 = temp;
}
// output
if(d >= 0)
{
cout << root1 << " ";
}
if(d > 0)
{
cout << root2 << " " <<endl;
}
if(d < 0)
{
cout <<"No Real Roots" << " ";
}
cin.get();
cin.get();
return 0;
}
Can someone help me out with the sample output. i get the 2nd integer, but i dont get the first.
Since this is homework I will only provide hints.
This line:
Code:
root2 = (-b + sqrt(d))/(2*a);
Contains a maths error, or the line above does depending on the way you look at it.
Also initialize all your variables with a value, you can not assume they have a consistent default value.
And lastly your indentation is terrible.
Rich
Visual Studio 2010 Professional | Windows 7 (x64)
Ubuntu
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
|