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

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.

Related

How can I set this so I can't enter any more than four numbers for cin?

I'm trying to make a simple user input. I tried to set it up so there would be four numbers entered by the user. It works for four inputs from user. It does not end after four separate numbers. Also managed to find out that I can trigger an endless repeating loop if one really long number is entered. Then I have to press cntrl+C to stop the code from running. This is in Microsoft Visual Studio if that is important.
#include <iostream>
using namespace std;
void GameBoy ()
{
cout<< "\nYou think you are this badass hacker so...." <<endl;
cout<< "Please enter the correct combination of numbers..." <<endl;
int a {};
int b {};
int c {};
int d {};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum)
{
cout << "You're a goober!!" << endl;
}
else
{
cout << "You're still an goober :-P" << endl;
}
}
int main()
{
while (true)
{
GameBoy ();
}
return 0;
}
You can modify your function to return bool (true if all numbers are in the correct range, false if some number is out of range). Something like this:
#include <iostream>
using namespace std;
bool GameBoy() {
cout << "\nYou think you are this badass hacker so...." << endl;
cout << "Please enter the correct combination of numbers..." << endl;
int a{};
int b{};
int c{};
int d{};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum) {
cout << "You're a goober!!" << endl;
} else {
cout << "You're still an goober :-P" << endl;
}
// if (Correct condition)
// return true;
// else Wrong condition
// return false
}
int main() {
while (GameBoy()) {
}
return 0;
}
I feel silly now. Just finished posting this question and found out what I needed to stop that endless loop. Once I added this then the issue stopped. Wow won't forget that!.
cin.clear();
cin.ignore();

Need to do compare without functions by using 3 variables on

Need to do compare without functions. I gotta do compare by using function just once and use no more 3 variables. Task that I got: need to tabulate (A to B, with h step) and show local minimum by “*”
——————————
#include <iostream>
#include "clocale"
#include "cmath"
#include <iomanip>
using namespace std;
// ------------------------- f(x) = x*sin(3*x) - 1 -------------------
double f(double x){
return x*sin(3*x) - 1;
}
// -------------------------------------------------------------------------------
int main()
{
setlocale(LC_ALL, "russian");
double A,B;
double h;
// ------------------ ---------------------
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
cout << "h = ";
cin >> h;
// ------------------------------------------------------
cout.setf(ios_base::fixed);
cout.precision(4);
for (double k=A; k<=B; k+=h){
if (f(k - h) >= f(k) && f(k + h) >= f(k)){
cout << "*";
}
else{
cout << " ";
}
cout << "x = " << k << " y = " << f(k) << "\n";
}
system("pause");
return 0;
}
I hope I guess right what you want to do. For each f(x) you want to compare that value to f(x-h) and f(x+h) to see if f(x) is a local minimum. You seem to have something, but you are recalculating f(x-h), f(x) and f(x+h) every time you use the value, when in fact on each iteration you only need to compute a single new value.
Just remember previous values. Note that the first point you can compare previous and next value is A+h, hence we start with
auto current = f(A+h);
auto previous = f(A);
auto next = f(A+2*h);
if (do the comparison of current vs previous and next) print something
// now the loop
for (double x = A+2*h; x < B; x+=h){
previous = current;
current = next; // in the first iteration this is f(A+2*h)
next = f(x+h);
if (do the comparison of current vs previous and next) print something
}
Note that now in each iteration only the next value is calculated, while current and previous are already known from the iteration before.
since you are trying to find local minima then you should try following code. this is exactly as you wanted but more robust.
#include <iostream>
#include "clocale"
#include "cmath"
#include <iomanip>
using namespace std;
// ------------------------- f(x) = x*sin(3*x) - 1 -------------------
double f(double x){
return x*sin(3*x) - 1;
}
// -------------------------------------------------------------------------------
bool is_minima(double a, double b, double c){
if(a > b && c > b){
return true;
else
return false;
}
int main()
{
setlocale(LC_ALL, "russian");
double A,B;
double h;
// ------------------ ---------------------
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
cout << "h = ";
cin >> h;
// ------------------------------------------------------
cout.setf(ios_base::fixed);
cout.precision(4);
for (double k=A; k<=B; k+=h){
if (is_minima(f(k-h),f(k),f(k+h))){
cout << "*";
}
else{
cout << " ";
}
cout << "x = " << k << " y = " << f(k) << "\n";
}
system("pause");
return 0;
}

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.

convert letters into numbers (A=1; B=2...) c++

I was trying to make letters into numbers in c++. When I write in console it should count modulo and type out if ship is coming (i did all, but can't make letters into numbers :/ )
This what should happen: ABC a = 1; b=2; c=3 1*2*3=6....
So I need to write a word and it should be separated into letters and converted into numbers like that.
I am just learning and I don't know much :)
My current code:
int shipnum, groupnum, moduleship, modulegroup;
cout << "type ship number "; cin >> shipnum;
cout << "type group number "; cin >> groupnum;
/*shipnum dabar 5... (5 mod 2)
groupnum dabar 3... (3 mod 2)
*/
moduleship = shipnum % 47; //skaiciuojam moduli...
modulegroup = groupnum % 47;
if (moduleship == modulegroup) {
cout << "YES ship is coming for you :)";
}
else if (moduleship != modulegroup) { // "!=" reiskia "nelygu"
cout << "SORRY, NO ship for you :(";
}
return 0;
Your question isn't precise, although I find it enough. Tip: Be precise with the information you provide, there's no need to show the rest of the code.
Lets say we have this char Ship[20]="ABCDEF";. If you encoding is as simple as A=1, B=2, etc, then you only need something like this:
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
decoded = decoded * i
}
cout<<decoded;
This loop will run till it encounters the '\0' (null character) at the end of the string. So, you would have a factorial on the fact that your codeing (A=1,B=2, etc) represents a factorial.
otherwise, you could use a switch case, or if statements to check for individual characters and decode appropriately.
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
switch(Ship[i]){
case 'A' : decoded = decoded * 1;
break;
case 'B' : decoded = decoded *2;
break;
//So on
default : break;
}
}
cout<<decoded;
Output in both cases:
720
"convert letters into numbers (A=1; B=2…)"
string a{"ABC"};
int a0 = a[0]; // 65
int a1 = a[1]; // 66
int a2 = a[2]; // 67
.....
want to wrap A = 1, B = 2...
a0 = a0 - (65 - 1);
a1 = a1 - (65 - 1);
....
The question is not clear but i think the question basically is to convert char into int which follows the encoding A=1, B=2, ......, Z=26 and do the required processing which is to multiply all the encodings.
So here is how you could do it:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s; //Input string
cout << "enter the string(CAPITALS ONLY) :";
cin >> s; //read the input string
int result = 1;
for (auto &elem : s){ //process all the characters of s
result *= elem - 'A' + 1; //corresponding int value is multiplied to the result
}
cout << "the result is :" << result;
}
Sample Output:
enter the string(CAPITALS ONLY) :AEF
the result is :30
(a+b)2=a2+b2+2ab: in cpp example
#include<iostream>
using namespace std;
//Declaring Function in scope
void firstFormula();
int main(void) //Main function
{
cout << "Hello World!!" << endl; //sample test text printing
firstFormula(); //executing function
return 0;
}
//function implementation
void firstFormula(){
//initializing variables
int a, b;
cout << "Enter Value of A" << endl;
cin >> a;//updating input values of a
cout << "Enter Value of B" << endl;
cin >> b;//updating input values of b
int v1 = a + b; //(a+b)2
int v2 = v1 * v1; //L.H.S
cout << "Value of v1=" << v1 << endl << "V2=" << v2 << endl;
cout << "Value of a=" << a << endl << "Value of B=" << b << endl;
int v3 = a * a;
int v4 = b * b;
int v5 = 2 * a * b;
int v6 = v3 + v4 + v5; //` R.H.S value after equation` `egfyufe`
cout << "Output=" << "V3=" << v3 << endl << "V4=" << v4 << endl << "v5="
<< v5 << endl << "V6=" << v6 << endl;
} //end

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.