[英]Void function (c++)
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.我想创建一个使用 2 个空函数求解二次方程(Ax²+Bx+C=0) 的程序:一个用于插入 A、B、C 的值,第二个用于求解方程。 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.当您声明像
void add_nmbr(int a, int b, int c)
这样的函数时void add_nmbr(int a, int b, int c)
您是按值传递参数,这意味着您将值的副本传递给函数。 You can change the value inside add_nmbr
for a
but that value stays inside the function.您可以为
a
更改add_nmbr
的值,但该值保留在函数内。 In you case, the variable a
in function main
stays un-initialized.在你的情况下,函数
main
的变量a
保持未初始化。
The same thing for resoudre
. resoudre
。 To fix it, you can use reference
, like this要修复它,您可以使用
reference
,就像这样
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.