我刚刚学C没多久,现在做 这道 题卡住了,恳请各位们能教教我接下来怎么改
(1)原代码的问题
#include <iostream> //<iostream>是C++的头文件,不是C的头文件
#include <math.h>
using namespace std; //C语言中不使用using namesapce std
int main()
{
double a, b, c;
scanf("%lf %lf %lf", &a, &b, &c);
double x;
x = b*b - 4 * a*c;
if (x == 0) {
printf("x1=x2=%.5lf", -b / 2 / a);
}
else if (x > 0) {
printf("x1=%.5f;x2=%.5f", (-b + sqrt(x)) / 2 / a, (-b - sqrt(x)) / 2 / a);
}
else(x < 0); { //这里直接使用else就可以了
//在a=1,b=0,c=1的特殊情形下,输出结果的实部前面会有负号
printf("x1=%.5f+%.5fi;x2=%.5f-%.5fi", -b / 2 / a, sqrt(-x) / 2 / a, -b / 2 / a, sqrt(-x) / 2 / a);
}
return 0;
}
(2)修改后的代码
#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c;
scanf("%lf %lf %lf", &a, &b, &c);
double x;
x = b*b - 4*a*c;
if (x == 0) {
printf("x1=x2=%.5lf\n", -b / 2 / a);
}
else if (x > 0) {
printf("x1=%.5lf;x2=%.5lf\n", (-b + sqrt(x)) / 2 / a, (-b - sqrt(x)) / 2 / a);
}
else {
if (b == 0)
{
printf("x1=%.5lf+%.5lfi;x2=%.5lf-%.5lfi\n", 0.0, sqrt(-x) / 2 / a,
0.0, sqrt(-x) / 2 / a);
}
else
{
printf("x1=%.5lf+%.5lfi;x2=%.5lf-%.5lfi\n", -b / 2 / a, sqrt(-x) / 2 / a,
-b / 2 / a, sqrt(-x) / 2 / a);
}
}
return 0;
}
(3)代码运行结果截图
else (x<0);改成else就行
我看到的问题是x为double类型然后就时if语句的判断x == 0有问题,因为x是double类型是存在误差的,即使是1-1,但是只要你将1表示的变量初始化为double类型1- 1 = 0.0000....014..,也就是不等于0.所以double等浮点数的类型是不能直接判断是否为0的。
根据你的问题要想判断是否为0可以这么写 x < 1e-6,其中1e-6表示10的-6次方,也就是当x小于某个数时足够小时我们认为它等于0
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
int main()
{
double x1,x2,a,b,c;
cin>>a>>b>>c;
if(a!=0)
{
x1=(-b+sqrt(b*b-4*a*c))/(2*a);
x2=(-b-sqrt(b*b-4*a*c))/(2*a);
if(x1==x2)
{
printf("x1=x2=%.5lf",x1);
}
else
{
if(x1<x2)
{
printf("x1=%.5lf;x2=%.5lf",x1,x2);
}
else
{
printf("x1=%.5lf;x2=%.5lf",x2,x1);
}
}
}
else
cout<<"No answer!";
return 0;
}