d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > I'm Trying To Get This Formula To Work > -_-
Add Reply New Topic New Poll
Member
Posts: 38,019
Joined: Feb 14 2011
Gold: 6.90
Sep 9 2015 02:53pm

// Trying to solve the equation provided in the Assignment paper
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double result,val;

cout << "this is the output of my first program" << endl;
for(val = -3.0; val <= 5.0; val += 0.5){
result = (-4.0 * val * val * val + 8.0 * val * val + 9.0 * val + 18) / (abs(7.0 - val * val * val) + (sqrt(3.0 * val * val + 10)));
cout << "val =" << val << "result =" << result << endl;
}
if(result = 0.0)
cout << "result is zero" << endl;
if(result > 0.0)
cout << "result is positive" << endl;
if(result < 0.0)
cout << "result is negative" << endl;
cout << "The program is finished";
return 0;
}

^ above formula is
result = -4val^3 + 8val^2 + 9val + 18
-------------------------------------
|7-val^3| + sqrt(3val^2 +10)

The answer is absolutely incorrect when I compile and run it.
I get random numbers and the if doesn't register for some reason, maybe thats also one reason why the formula is wrong?
When val = 2. result = 0
But I get like 6.2 something

This post was edited by Uguu on Sep 9 2015 03:02pm
Member
Posts: 9,803
Joined: Jun 28 2005
Gold: 6.67
Sep 9 2015 04:26pm
Use [​code][​/code] tags.

Format your code, what you have now is ugly.

Isn't this much nicer? ( you can use http://format.krzaq.cc/ to do this easily )
Code
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double result, val;

cout << "this is the output of my first program" << endl;
for (val = -3.0; val <= 5.0; val += 0.5)
{
result = (-4.0 * val * val * val + 8.0 * val * val + 9.0 * val + 18)
/ (abs(7.0 - val * val * val) + (sqrt(3.0 * val * val + 10)));
cout << "val =" << val << "result =" << result << endl;
}
if (result = 0.0)
cout << "result is zero" << endl;
if (result > 0.0)
cout << "result is positive" << endl;
if (result < 0.0)
cout << "result is negative" << endl;
cout << "The program is finished";
return 0;
}


Finally: if (result = 0.0) -- a single = is an assignment, not comparison. == is comparison, but you're using floating point numbers, and with those, exact comparison is almost always incorrect. You should check if the result is within an epsion of 0, for example:

Code
double const epsilon = 0.001;
if (abs(result) < epsilon)
cout << "result is zero" << endl;
else if (result > 0.0)
cout << "result is positive" << endl;
else if (result < 0.0)
cout << "result is negative" << endl;



This post was edited by KrzaQ2 on Sep 9 2015 04:30pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll