I have the following problem : I write my code with the Qt IDE. I was informed that when people try to compile it with other IDE's (like codeblocks, or visual studio) The output they get is different and that there are maufunctions. Any ideas what can be causing this ? I will give you an example:
This is Newton's Method with a function who's root is 2.83something. I get the same, correct calulations each time I run it in Qt. I get "nan" in code blocks and something irrelevant as well in visual studio. I don't understand, do I have a mistake somewhere in my code ? What can be causing this ?
#include <iostream>
#include <cmath> // we need the abs() function for this program
using namespace std;
const double EPS = 1e-10; // the "small enough" constant. global variable, because it is good programming style
double newton_theorem(double x)
{
double old_x = x; // asign the value of the previous iteration
double f_x1 = old_x*old_x - 8; // create the top side of the f(x[n+1] equation
double f_x2 = 2 * old_x; // create the bottom side
double new_x = old_x - f_x1 / f_x2; // calculate f(x[n+1])
//cout << new_x << endl; // remove the // from this line to see the result after each iteration
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
newton_theorem(new_x);
}
}// newton_theorem
int main()
{
cout << "This program will find the root of the function f(x) = x * x - 8" << endl;
cout << "Please enter the value of X : ";
double x;
cin >> x;
double root = newton_theorem(x);
cout << "The approximate root of the function is: " << root << endl;
return 0;
}//main
Yes, you run into undefined behavior:
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
/*return*/ newton_theorem(new_x); // <<--- HERE!
}
Missing a return on the else branch.
We could try to explain why Qt works (its compiler automatically puts the result of newton_theorem in the return registry, or shares registries, or whatever), but the fact of the matter is anything can happen. Some compilers might behave the same on subsequent runs, some might crash all the time.
Related
Here is the problem I must do(Just for context): Write a program that will input 2 integers from the user, will then calculate the first to the power of the second and then output the result. The Input, calculation and output should be in three separate subprograms/functions. You must calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times. For this homework only, you are allowed to use global variables to move information between functions.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
double a, b, ans;
int main()
{
cout << "Please enter two whole numbers: ";
cin >> a >> b;
cout << conclusion() << calc();
system("pause");
return 0;
}
int calc()
{
double ans = pow(a, b);
return 0;
}
int conclusion()
{
cout << a << " To the power of " << b
<< " is " << ans;
return 0;
}
So here's what I'm having an issue with, I do online classes. The dude is like, "here's a problem, figure it out and just do it." Which is fine I guess, but when things like this come up its hard to find certain tutorials and questions. Anyway, I got my BASE code down. Now I need a while loop, and have no idea what this means: calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times.
I figured I could just do a while and do
double ans = pow(a, b);
But that's not the case apparently. That's what my chapter taught me, but not with a while and all this extra stuff you need to do for this. I asked a classmate, she said she had a really difficult time as well, and her example to me was:
int a = 0;
int b = 0;
int c = 1;
cin >> a;
cin >> b;
int powerOp(int a, int b, int c)
{
while (b > 0)
{
c = c * a;
b--;
}
cout << c;
return c;
}
I have been working almost all day and can't figure this out. I don't understand why we need to factorize and set the int = 1. I thought it could simply be
double ans = pow(a, b); //a and b being the 2 numbers the user inputs
Its pretty simple, lets say you have 2^3. You and I both agree that it is the same as doing 2x2x2. You mutiplied you first number A by itself B (your second number) times. Now for your loop, what you want have your second number server as your counter AND loop exit condition. Something like this
double YourPowerFunction(int a, int b)
{
int counter = 0;
double result = 1;
while (counter < b)
{
counter++:
result = result * a;
}
return result;
}
Okay so I'm pretty sure I found the answer. Result is the variable for ans
int calc() //function for calculation
{
//Still not sure how I did this one, after hours of playing around with it
while (b > 0) //This code is adding a 0 in the result. I can't figure it out
{
result = result * a;
b--;
}
return (result);
}
This is just a simple solution, as it wants to add a 0 in the end result.
So this is my code
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int kol=0, x;
cout << "Insert a number: ";
cin >> x;
while (x > 0);
{
div_t output;
output = x;
x = div(output, 10);
kol += kol;
}
cout << "Amount: " << kol << endl;
system ("pause");
return 0;
}
And I got this error:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversation)
Can someone tell me what I did wrong, and how to fix?
You are treating div_t like an int; it isn't one. It's a struct.
See http://en.cppreference.com/w/cpp/numeric/math/div
Can you expound on what you are trying to do? Clearly, there's repetitive division intended, but that's all I surmise.
output is a div_t. x is an int, so output = x is like trying to assign an apple to an orange. You can't do it without establishing a set of rules for turning the apple into an orange.
We could try to write such a rule, but why bother? Instead let's look at the code that got us into this predicament and try to figure out the context.
while (x > 0);
{
div_t output;
output = x;
x = div(output, 10);
kol += kol;
}
The purpose of this loop seems to be to count of the number of times x was divided by ten and store the count in kol.
div_t is the result of a call to div, so assigning a value to the result before performing the operation that will generate the result is a touch unusual. Perhaps OP meant
while (x > 0);
{
div_t output;
output = div(x, 10);
kol += kol;
}
to divide x by ten and get the quotient and remainder.
But this loop will never exit because x is never changed. If it is not zero, the loop will never terminate and if it is zero the loop will never enter. Perhaps
while (x > 0);
{
div_t output;
output = div(x, 10);
x = output.quot;
kol += kol;
}
would be more appropriate. The remainder is never used however, so div is effectively wasted and
while (x > 0);
{
x = x / 10; // or x /= 10;
kol += kol;
}
would provide the same result with far less fuss.
I am supposed to get the following code to display something along the lines of: "The sum of 1 to 10 is 55." (The larger number can be any number that was just the example I got.) I was given this code to use.
#include <iostream>
using namespace std;
// Compute the sum of all of the numbers from 1 to n where n
// is a natural number
// use the formula: n(n+1)/2
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
int main()
{
int sum = 0;
int maxNumber;
// get the maxNumber for the function call
cout << "Enter a whole number greater than 0" << endl;
cin >> maxNumber;
// call compute sum
compute_sum(maxNumber); // Call to compute_sum function
// display the sum calculated by the compute_sum function
cout << "The sum of 1 to " << maxNumber;
cout << " is " << sum << endl;
return 0;
}
I do not understand how funcctions work at all and do not have any idea how I would go about getting this to work. The only thing I know about this (and this is from the teacher) is that the change required is not major. "Note: If you are making major changes to the main and compute_sum funtions you are probably
doing way too much work." I have tried changing the function to an int function with a return but I could not get it to work properly (most likely due to not knowing how functions work). So can someone please help me?
The part you're missing is the return type of the function, and then to actually return that value from the function.
At the moment you have
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
A function prototype in C looks pretty much like this
<return type> <name> (<parameters>)
{
// your logic here
return <your_own_variable> // Note: You can omit this if the return type is void (it means the function doesn't return anything)
}
You want to modify your function so you are returning the integer value you're calculating inside of it
int compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
return sum_to_limit;
}
So what happens is after main runs, when the the point of execution hits
compute_sum(maxNumber);
The program flow jumps to that function and executes the code inside of it. When the function finishes, it returns the value back to where it was originally called from. So you also need to add this to store the value returned
int result = compute_sum(maxNumber);
and then make sure to output that value to the user.
You can also make the computer_sum function a little more terse my not storing a temporary variable, you can just do this
int compute_sum(int limit) // compute_sum function
{
return limit * (limit + 1) / 2;
}
I hope that helps. There's a lot more going on behind the scenes but that's the basic idea. Good luck! :)
In the program below, I am trying to calculate the distance between two points. For this, I have made two Point objects. In the method that returns the distance, I have used the distance formula to calculate distance between two points in space. However, every time I run the program, I get a not a number value, which shouldn't be there. Please help.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
class Point
{
public:
Point(int a, int b);
~Point();
double getDistance(Point& P2);
void setPoints(int a, int b);
int getX();
int getY();
private:
int x;
int y;
};
Point::Point(int a, int b)
{
setPoints(a,b);
}
Point::~Point()
{
//Nothing much to do
}
void Point::setPoints(int a, int b)
{
x = a;
y = b;
}
double Point::getDistance(Point& P2)
{
int xdiff = P2.getX()-this->getX();
int ydiff = P2.getY()-this->getY();
xdiff = xdiff*xdiff;
ydiff = ydiff*ydiff;
double retval = sqrt((xdiff) - (ydiff));
return retval;
}
int Point::getX()
{
return x;
}
int Point::getY()
{
return y;
}
int main(int argc, char* argv[])
{
Point P1(0,0);
Point P2(0,1);
Point& pr = P2;
cout<<P1.getDistance(pr)<<endl;
return 0;
}
Your formula is wrong. It's not
sqrt(xdiff - ydiff)
but
sqrt(xdiff + ydiff)
You're trying to get the sqrt(-1) which is indeed not a number (or not a real number).
Here's how to figure this sort of thing out for yourself, or at least get a lot closer to a good StackOverflow question:
You know the problem is in the sqrt() call. So, what is it being called with? In this case, you could trace through the computation manually:
int xdiff = P2.getX()-this->getX(); // this is 0 - 0, which is 0.
int ydiff = P2.getY()-this->getY(); // this is 1 - 0, which is 1.
xdiff = xdiff*xdiff; // this is still 0.
ydiff = ydiff*ydiff; // this is still 1.
double retval = sqrt((xdiff) - (ydiff)); // this is sqrt(0 - 1), or sqrt(-1).
Alternately, in more complicated cases -- and to check your work, you could either use a debugger to print out the values of the arguments, or you could insert print statements:
xdiff = xdiff*xdiff;
ydiff = ydiff*ydiff;
cout << 'xdiff: ' << xdiff << ' ydiff: ' << ydiff << endl
cout << 'computing sqrt(' << xdiff - ydiff << ')' << endl
double retval = sqrt((xdiff) - (ydiff));
Either way, you now know that you're computing sqrt(-1), and you can try running that directly to confirm that it does indeed produce the same result. So either you have a question of "Why is sqrt(-1) returning NaN?" or a question of "Why is my distance calculation trying to compute the square root of a negative number?"
Hopefully you already know the answer to the first question, and the second question should indicate that you need to double-check your distance formula, which should have showed you the answer pretty quickly -- but even if you can't figure out why it's doing that, it at least makes a more useful question to ask here.
You should be adding here, not subtracting:
double retval = sqrt((xdiff) - (ydiff)); // correct is +
Subtracting causes you to take the square root of -1 due to the input data, which is not a (real) number.
As craigmj said, the formula for distance is sqrt ((x1-x2) + (y1-y2)). It's addition not subtraction. What your doing is generating an imaginary number (sqrt (-1)) which will cause an error.
Just a tip of advice, but do not create the destructor if it doesn't do anything; a destructor will be provided for you. Adding a destructor that doesn't do anything just adds unneeded code and makes it look messier.
Also in the getDistance function, you do not need to use this ->getX() and this-> getY(). Since this is a member function it has access to private data, therefore you can directly access the variables through x and y.
I have a school problem but I do not understand what it actually asks. Any of you have an idea what it's really asking for? I don't need code, I just need to understand it.
This is the problem:
Construct a computer program that uses the Secant method to solve the problem:
f(x) = (1+x) cos( sin(x)3 ) - 1.4 = 0
Starting with the initial guesses of x=2.0 and x=2.1, obtain an approximation to x such that |f(x)| < 0.0000001.
This is my code from what I understand, but I think I'm not understanding the question correctly.
#include <iostream>
#include <cmath>
double secant(double x);
using namespace std;
int main()
{
double x = 2.0;
double r = 0.0;
int counter = 0;
while( r < 0 && counter <= 40)
{
r =secant(x);
cout << "x: " << x << ", f(x): " << r << endl;
counter++;
x += 0.1;
}
return 0;
}
double secant(double x)
{
double r;
r = (1+x) * cos(pow(sin(x), 3.0)) - 1.4;
return r;
}
You are supposed to use the Secant Method: http://en.wikipedia.org/wiki/Secant_method
Follow the method as described in the article. It is an iterative method much like Netwon's method. You'll need to make a function to evaluate x(n+1) given x(n) and iterate it until your margin of error is less than specified.
The coding side of this may prove fairly straightforward as long as you know what the secant method is. Also, that page has a code example. That should prove pretty useful. :)