注册 登录
编程论坛 C++教室

急~~~会C++的大侠来帮忙看看~小弟新学C++两天..

lerncav 发布于 2010-07-26 17:42, 827 次点击
我前两天看那个《易学C++》,今天没事试着做,
然后想做个关于二次函数,就是Y=AX^2+BX+C的。


我的意思是,创建一个字符变量M,然后让别人输入“Y,X,A,B,C”其中一个字母的,
然后就判断去求哪个,再通过表达式求出来,比如说别人输入字符Y,就是求Y,然后让别人再输入A,B,C,X,就能求出来Y的值。


我试着执行了一下,求A,B,C,Y的值都行,而求X的值时候求出来的就不对,希望哪位大侠可以帮忙纠正一下错误,然后告诉我这样做的原因,小弟谢谢了!!!!

以下是小弟写的:




#include"iostream.h"
#include"math.h"
int main()
{
 char m;
 cin>>m;
 double a,b,c,x,y;
 if(m=='y')
 {
  cin>>a>>b>>c>>x;
  y=a*x*x+b*x+c;
  cout<<y<<endl;
 }
 if(m=='a')
 {
  cin>>b>>c>>x>>y;
  a=(y-b*x-c)/(x*x);
  cout<<a<<endl;
 }
 if(m=='b')
 {
  cin>>a>>c>>x>>y;
  b=(y-a*x*x-c)/x;
  cout<<b<<endl;
 }
 if(m=='c')
 {
  cin>>a>>b>>x>>y;
  c=y-a*x*x-b*x;
  cout<<c<<endl;
 }
 if(m=='x')
 {
  int x2,temp;
  cin>>a>>b>>c>>y;
  temp=b*b-4*a*c;
  if(temp>=0)
  {
   sqrt(temp);
   x=(0-b-temp)/2*a;
   x2=(temp-b);
   cout<<x<<x2;
  }
  else
  {
   cout<<"Error!";
  }
 }
 else
 {
  cout<<"Error!";
 }
 return 0;
}






8 回复
#2
leftwing2010-07-26 18:27
楼主的sqrt(temp);这句有问题,他是需要用一个变量来接收返回值的,光是调用这句sqrt()是不能改变temp的值的。所以这里导致后面都错了吧应该
#3
slamjam2010-07-27 14:23
  楼上说的也对 ,补充一点,我记得 sqrt 好像只能接受 浮点数作参数, 你试一下 吧 temp 定义成double的,
#4
gq1987182010-07-27 14:43
程序代码:
#include"iostream"
#include"cmath"
using namespace std;
int main()
{
char m;
cin>>m;
double a,b,c,x,y;
if(m=='y')
{
  cin>>a>>b>>c>>x;
  y=a*x*x+b*x+c;
  cout<<y<<endl;
}
if(m=='a')
{
  cin>>b>>c>>x>>y;
  a=(y-b*x-c)/(x*x);
  cout<<a<<endl;
}
if(m=='b')
{
  cin>>a>>c>>x>>y;
  b=(y-a*x*x-c)/x;
  cout<<b<<endl;
}
if(m=='c')
{
  cin>>a>>b>>x>>y;
  c=y-a*x*x-b*x;
  cout<<c<<endl;
}
if(m=='x')
{
  int x2;
  double temp;
  cin>>a>>b>>c>>y;
  temp=b*b-4*a*c;
  if(temp>=0)
  {
   sqrt(temp);//sqrt参数的类型要注意
   x=(0-b-temp)/2*a;
   x2=(temp-b);
   cout<<x<<x2;
  }
  else
  {
   cout<<"Error!";
  }
}
else
{
  cout<<"Error!";
}
return 0;
}
sqrt参数的类型:
double sqrt(double x);
float sqrtf(float x);
long double sqrtl(long double x);
#5
dream_one2010-08-01 08:00
   sqrt(temp);
   x=(0-b-temp)/2*a;
   x2=(temp-b);
可以改为:
temp=sqrt(temp);
   x=(-b-temp)/(2*a);
   x2=(temp-b)/(2*a);
#6
xxlovemf2010-08-01 18:41
学c++两天就能写出这样
怀疑?
#7
xxlovemf2010-08-01 18:42
不过 说实话 你这写的也够基础的了了
#8
ragnaros2010-08-02 16:47
程序代码:
#include"iostream"
#include"cmath"
using namespace std;
int main()
{
char m;
cin>>m;
double a,b,c,x,y;
if(m=='y')
{
  cin>>a>>b>>c>>x;
  y=a*x*x+b*x+c;
  cout<<y<<endl;
}
if(m=='a')
{
  cin>>b>>c>>x>>y;
  a=(y-b*x-c)/(x*x);
  cout<<a<<endl;
}
if(m=='b')
{
  cin>>a>>c>>x>>y;
  b=(y-a*x*x-c)/x;
  cout<<b<<endl;
}
if(m=='c')
{
  cin>>a>>b>>x>>y;
  c=y-a*x*x-b*x;
  cout<<c<<endl;
}
if(m=='x')
{
  int x2;
  double temp;           //temp定义为double类型
  cin>>a>>b>>c>>y;
  temp=b*b-4*a*c;
  if(temp>=0)
  {
   temp=sqrt(temp);      //sqrt参数的类型要注意
   x=(0-b-temp)/(2*a);   //这里2*a要加括号,x=(-b-sqrt(temp))/(2*a)
   x2=(temp-b)/(2*a);   //这里要除以2*a,并且要加括号,x=(-b+sqrt(temp))/(2*a)
   cout<<x<<x2;
  }
  else
  {
   cout<<"Error!";
  }
}
else
{
  cout<<"Error!";
}
return 0;
}
#9
lerncav2010-08-03 15:05
谢谢指导..
1