I want to create a program that solve quadratic equation (Ax²+Bx+C=0) using 2 void functions: one to insert the values of A,B,C, and the second for solving the equation. This is what I did:
#include <iostream>
#include <math.h>
using namespace std;
void add_nmbr(int a, int b, int c){
int *pa,*pb,*pc;
cout << "Entrer le nombre A " <<endl;
cin >> a;
cout << "Entrer le nombre B " <<endl;
cin >> b;
cout << "Entrer le nombre C " <<endl;
cin >> c;
pa = &a;
pb = &b;
pc = &c;
cout << a <<"x2 + "<<b<<"x + "<<"c = 0"<<endl;
}
void resoudre(int a,int b, int c){
double delta;
double x1,x2;
delta= b*b-4*a*c ;
if (delta<0){
cout << "Pas de solution !"<<endl;
}else{
x1=(-b-(sqrt(delta)))/(2*a);
x2=(-b+(sqrt(delta)))/(2*a);
}
cout << a <<"x2 + "<<b<<"x + "<<"c = 0"<<endl;
cout << "la solution est : " << x1 << endl;
cout << "la solution est : " << x2 << endl;
}
int main()
{
int a,b,c;
add_nmbr(a,b,c);
resoudre(a,b,c);
return 0;
}
When you declare a function like void add_nmbr(int a, int b, int c)
you are passing parameters by value which means you pass a copy of value into the function. You can change the value inside add_nmbr
for a
but that value stays inside the function. In you case, the variable a
in function main
stays un-initialized.
The same thing for resoudre
. To fix it, you can use reference
, like this
void add_nmbr(int &a, int &b, int &c) {...}
Look at this;
void add_nmbr(int& a, int& b, int& c){
cout << "Entrer le nombre A " <<endl;
cin >> a;
cin.ignore(); //Use it after cin because of you hitting enter after getting the value.
cout << "Entrer le nombre B " <<endl;
cin >> b;
cin.ignore();
cout << "Entrer le nombre C " <<endl;
cin >> c;
cin.ignore();
cout << a <<"x2 + "<<b<<"x + "<<"c = 0"<<endl;
}
But yeah, you should try to read up on call by refence and call by value.
Why you dont use reference ?
Like that
void add_nmbr(int& a, int& b, int& c) { cout << "Entrer le nombre A " << endl; cin >> a; cout << "Entrer le nombre B " << endl; cin >> b; cout << "Entrer le nombre C " << endl; cin >> c; cout << a << "x2 + " << b << "x + "<<"c = 0"<< endl; } void resoudre(const int &a,const int &b, const int &c) { double delta; double x1,x2; delta= b*b-4*a*c ; if (delta<0){ cout << "Pas de solution !"<< endl; }else{ x1=(-b-(sqrt(delta)))/(2*a); x2=(-b+(sqrt(delta)))/(2*a); } cout << a <<"x2 + "<< b << "x + "<< "c = 0"<< endl; cout << "la solution est : " << x1 << endl; cout << "la solution est : " << x2 << endl; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.