Why does this code produce strange, unexpected output? - c++

Why am I not getting a proper result?
I don't get a proper output of px although I have it named as a double I am getting some freaking number-text mashup as a result.
#include <iostream>
using namespace std;
int main(){
double a = 0; double b = 0; double c = 0; double x = 0;
cout << "Welcome to Lytis! \nPlease enter a:";
cin >> a;
cout << "Please enter b:";
cin >> b;
cout << "Please enter c:";
cin >> c;
if (a != 0){
double d = (b*b) - (4 * a * c);
}
f (d == 0){
double x = -(b) / (2 * a);
double *px = &x;
cout << "The only solution is x=" << px;
cin.get();
}
What am I missing?

1) Your code does not compile (e.g. d is not declared)
2) The "number-text meshup" is the address of x (the pointer) that you are printing out.
Use the dereference operator * to get the value pointed to :
cout << "The only solution is x=" << *px;
^^^
Here
3) You should check the return value of cin to be safe against wrong inputs.
4) "Lytis" means "Sex" in Lithuanian.

It appears px is of type double *, so outputting it as such is printing out a memory location (usually expressed in hexadecimal, i.e. 0-9 A-F ).
The assignment double *px = &x is legit, as it is assigning a reference (memory location) to a pointer, but when you output a pointer with cout it will display its location.
Maybe try:
cout << "The only so....." << *px;

Related

C++ : How to use a pointer in an if statement condition

I am writing a program that takes in 3 user inputted values for a quadratic equation, does some calculation, and returns how many roots the quadratic has.
When I print *(point), it gives me the correct value from the function.
However, when I use *(point) in the If conditions, it does not seem to work the way I want it to - I believe that *(point)is always some positive number, hence why it always executing that specific if condition.
The user values: a = 9, b = -12, c = 4 should print out This quadratic has 1 root. and the values: a = 2, b = 16, c = 33 should print out This quadratic has 2 roots. BUT the program always prints out This quadratic has 0 roots. no matter what the values entered.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
float *quadratic(float a1[]);
int main()
{
float a1[3] = {};
float *point;
cout << "Enter a: ";
cin >> a1[0];
cout << "\nEnter b: ";
cin >> a1[1];
cout << "\nEnter c: ";
cin >> a1[2];
point = quadratic(a1);
cout << endl << "d = " << *(point) << endl;
if (*(point) < 0) {
cout << "\nThis quadratic has 2 roots.\n";
}
else if (*(point) > 0) {
cout << "\nThis quadratic has 0 roots.\n";
}
else { //else if *(point) is equal to 0
cout << "\nThis quadratic has 1 root.\n";
}
return 0;
}
float *quadratic(float a1[]) {
float d;
d = (a1[1] * a1[1]) - (4 * a1[0] * a1[2]);
float xyz[1] = { d };
return xyz;
}
Your function quadratic returns a pointer to a local array. After the function return that array doesn't exist anymore. The pointer is then a dangling pointer, a pointer pointing to a place in memory that has once held an object, but that now may hold anything or just rubbish.
Since the array that quadratic attempts to return is always one value there is no need for returning an array. Just return that value.
You don't even need to deal with arrays for the polynomial's coefficients, since they're always three, but if array seems better than individual a, b and c variables, then just use std::array, e.g. like this:
#include <iostream>
#include <array>
#include <vector>
using namespace std;
using Float = double;
auto square_of( Float const v ) -> Float { return v*v; }
auto determinant( array<Float, 3> const& a )
-> Float
{
return square_of( a[1] ) - 4*a[0]*a[2];
}
auto main()
-> int
{
array<Float, 3> a;
cout << "Enter A: "; cin >> a[0];
cout << "Enter B: "; cin >> a[1];
cout << "Enter C: "; cin >> a[2];
Float const d = determinant( a );
cout << "d = " << d << endl;
if( d < 0 )
{
cout << "This quadratic has 2 roots." << endl;
}
else if( d > 0 )
{
cout << "This quadratic has 0 roots." << endl;
}
else // d == 0
{
cout << "This quadratic has 1 root.";
}
}
The code above is equivalent to what I perceived as the intent of your code.
However, I'd check out the formula for roots of quadratic equations, and test the program, before handing in something.

Not able to figure out what is happening with the universal array

I have created a program which takes an equation. from the user by asking about the degree of the equation. and then taking the co-efficients from the user and then forming the function which results into an equation. and then I have used the bisection method to solve it.
The program is::
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
int stop=0,d,t[]={1};
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
int *t = new int[d+1];
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
return sum;
}
int main()
{
float a , b , c , i , j ;
A:
cout << " Enter the starting point of interval " <<endl;
cin >> a ;
cout << " Enter the end point of interval " << endl;
cin >> b ;
cout << " Enter the number of iterations to be done . ( More the iterations , accurate is the result ) " << endl;
cin >> i ;
for(j=0;j<i;j++)
{
if(f(a)*f(b)>0)
{
cout << " The root of the above polynomial does not lies in the given interval . TRY AGAIN " << endl;
goto A;
}
else
{
c = a + b ;
c = c / 2 ;
if (f(a)*f(c)>0) a = c ;
else b = c ;
cout <<"hello"<< a << "aa \t" << b << "\t" << c << endl;
}
}
cout << "Root = "<< c <<endl;
}
When the user gives the value of degree it creates an array of size one more than degree is created then there is a for loop which takes the value of co-efficients in that array . The problem is the value of the array stays intact till the first for loop . but as the control proceeds to the second loop ( see the two comments ) the value of the array is gone...I am using CodeLite ...guys help me?????
To solve the array issue you just need to make a few small changes.
int stop=0,d,*t; // Declare an uninitialized pointer to int
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
t = new int[d+1]; // Remove the int and asterix before t. You want to assign the new array to the pointer, not the value the pointer is pointing to.
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
delete[] t; // All new'ed things need to be deleted to not cause a leak. Delete it here since it is no longer needed.
return sum;
}
Please note that even if this works, it is not advised to use raw pointers in C++. Better to use an std::array<int> or std::vector<int> so you don't have to take care of the allocating and deleting of memory.
EDIT: Accidentaly left the int in fron of t. Changed now.

Adding a Probability Equation Into the Program

I've been working on this program in which it should calculate the probability based on the following formula:
𝑃(𝑥) = (𝑁!) / (𝑥!) * (𝑁−𝑥)!) * (p^x) * ((1-p)^(N-x))
Also, when the user types in a value, N must be an integer, x must be an integer which can be between 0 and N, and p must be a positive real number between 0 and 1. Till now this part works just fine but I don't know how to properly add the probability formula in the program.
The following is my code so far:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long int factorial (int N, int x, int p);
int main ()
{
double N, x, p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
return 0;
}
Can anyone help me out just to understand how to properly add an equation in my program?
Thank you!
This is my new code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial (double N, double x, double p);
int main ()
{
double N;
double x;
double p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
double Probability;
Probability = factorial(N, x, p);
cout << "Probability= " << Probability << endl;
return 0;
}
double factorial (double N, double x, double p){
double answer = ((tgamma(N+1))/((tgamma(x+1)) * (tgamma((N-x)+1)))) * (pow(p,x)) * (pow((1-p),(N-x)));
return answer;
}
The program recognizes the values I put in the system but when it calculates the answer, it gives a really small number. I tried out each section of the formula to make sure their was not a mistake but everything works fine when I tested it independently. Does anyone know what's wrong with the equation?
Thank you!
First you need to write a factorial function, check out this stackoverflow link:
How do you implement the factorial function in C++?
Then just write a function for your calculation. Assuming your factorial function is called getFact(int n) then:
double solve(int N, int x, double p) {
double answer = ( getFact(N)/getFact(x) )*getFact((N-x))* pow(p,x)* pow((1-p),(N-x));
return answer;
}
Then call the solve function in your main after having set your values.
double P_x;
P_x = solve(N,x,p);
Also, I use doubles because they can be more accurate, especially for p since its is 0 <= p <= 1.

Using pointers and arrays to solve linear system

I've been assigned a problem that asks us to solve a 2 equation system using an array and a pointer to that array. It's sort of a linear algebra way of going about it, with x_1 = (DE-BF)/(AD - BC) and x_2 = (AF - CE)/(AD - BC). The system is Ax_1 + Bx_2 = C and Dx_1 + Ex_2 = F. My code compiles fine but spits out garbage. Can anyone help me? I'm sure it's an error with my pointers but I don't know how to correct it. Much thanks in advance.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(){
double A,B,C,D,E,F;
cout << "Please enter a value for A: " << endl;
cin >> A;
cout << "Please enter a value for B: " << endl;
cin >> B;
cout << "Please enter a value for C: " << endl;
cin >> C;
cout << "Please enter a value for D: " << endl;
cin >> D;
cout << "Please enter a value for E: " << endl;
cin >> E;
cout << "Please enter a value for F: " << endl;
cin >> F;
double paramarray[6] = {A,B,C,D,E,F};
double* p;
p = &paramarray[6];
double x1 = (p[3]*p[4] - p[1]*p[5])/(p[0]*p[3] - p[1]*p[2]);
double x2 = (p[0]*p[5] - p[2]*p[4])/(p[0]*p[3] - p[1]*p[2]);
cout << "X_1 = " << x1 << endl;
cout << "X_2 = " << x2 << endl;
int f;
cin >> f;
return 0;
}
p = &paramarray[6];
This is the problem. This means you are assigning the address of paramarray[6] to p. paramarray[6] is not defined and you are trying to access out of bounds array.
Try changing it to
p = paramarray;
Also, it will be better if you first check for zero denominator and update your equation accordingly.
Your pointer should be initialized with the base of the array which is the address of the first element. And in your program you are initializing it to a address out of bounds which is the index 6 where the last index of the array is 5 itself.
An array of size six means the first index is 0 and the last index is 5.
so change your line:
p = &paramarray[6];
to
p = paramarray; //or p=&paramarray[0].Both are same here
This above line will store the address of the first element in pointer p.

Function not working correctly?

I am trying to create an exponent function and it does not seem to work as expected. Sorry if I don't understand some basic things, I'm just learning bits and pieces off the internet.
float x;
float y;
float z;
int h;
int j;
float exponent (float a, float b)
{
float r;
while(b > 1)
{
r = a * a;
b = b - 1;
}
return (r);
}
^Snippet of the function with variables.
cout << "EXPONENT MODE\n\n";
cout << "Please enter a number: ";
cin >> x; system("CLS");
cout << "Please enter another number as the exponent for the first: ";
cin >> y;
z = exponent(x, y);
cout << "Calculating the answer, please wait";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << "\n\nYour answer is : ";
cout << r;
Sleep(5000);
system("CLS");
cout << "Would you like to calculate another set of numbers? (yes = 1, no = 2) : ";
cin >> h;
system("CLS");
^Part I want to execute on the console.(Just code)
Basically, I want the user to input 2 numbers, the first(x) being the base number, the second(y) being the exponent. The program should input x as a and y as b and run the function. What happened: Input 1: 5, Input 2: 3, Expected: 125, Received: 25. I'm thinking about changing the while to (b > 0). If you guys could help that would be great!.
(Also don't judge me on the system("CLS") in the code)
It's fairly simple, you're printing the wrong variable.
cout << "\n\nYour answer is : ";
cout << r;
r is a local member variable of exponent. In the scope of main, the result of exponent was actually stored in a variable called z
z = exponent(x, y);
The fix is just to change your answer printing code to
cout << "\n\nYour answer is : ";
cout << z;
For your own benefit, you might want to try giving your variables more meaningful names and only declaring them in scopes where they are actually needed. I don't see you using r elsewhere in main, did you make it global in an attempt to try and make the r in exponent accessible there too?
I dont under stand what #kfsone is talking about.
but in the loop r is set as a*a everytime, isn't this why you are getting the square instead of exponent ? I think what you really want to do is this:
r=1
while( ...
r *= a;// note to accumulate result on r
b --;