第四章作业第三编程题

  1. 第三题普通代码
//第三题答案
#include <stdio.h>
#include <math.h>
#define DELTA   b*b -4*a*c
int main()
{
	double a, b, c;
	printf("求ax^2+bx+c=0的解,输入a,b,c:");
	scanf_s("%lf %lf %lf", &a, &b, &c);
	if (DELTA >= 0)
	{
		if (DELTA > 0)
		{
			printf("x1 = %lf x2 = %lf\n", (-b + sqrt(DELTA)) / (2 * a), (-b - sqrt(DELTA)) / (2 * a));
		}
		else
		{
			printf("x1 =x2= %lf\n", -b / (2 * a));
		}
	}
	else
	{
		printf("无解\n");
	}
}
  1. 考虑到a≠0
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define DELTA   b*b -4*a*c
int main()
{
	double a, b, c;

	printf("请输一元二次方程的三个系数a、b、c:\n");
	scanf_s("%lf %lf %lf", &a, &b, &c);
	if (0 == a && b != 0)
	{
		printf("x = %f\n", -c / b);
	}
	else if (0 == a && 0 == b && 0 == c)
	{
		printf("x = 全体实数\n");
	}//以上两种情况不属于一元二次方程,但是最好也考虑一下,因为后面的a会作为分母
	else if (DELTA >= 0)
	{
		if (DELTA > 0)
		{
			printf("x1 = %lf x2 = %lf\n", (-b + sqrt(DELTA)) / (2 * a), (-b - sqrt(DELTA)) / (2 * a));
		}
		else
		{
			printf("x1 = %lf\n", -b / (2 * a));
		}
	}
	else
	{
		printf("无解\n");
	}
	system("pause");
}
  1. 另一种形式
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[]) {
	int a, b, c;
	printf("求ax^2+bx+c=0的解,输入a,b,c:");
	scanf_s("%d%d%d", &a, &b, &c);
	if (pow(b, 2) - 4 * a * c < 0)
	{
		printf("此方程无解!");
	}
	else if (pow(b, 2) - 4 * a * c == 0)
	{
		printf("方程有一解,解为%d", -b / (2 * a));
	}
	else if (pow(b, 2) - 4 * a * c >= 0)
	{
		printf("方程有两解,解分别为%f,%f", (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a), (-b - sqrt(pow(b, 2) - 4 * a * c)) / (2 * a)); //输出两解 
	}
	else
	{
		printf("输入错误!");
	}
}
  1. 完整型,实数虚数
#include <stdio.h>
#include <math.h>
int main()
{
	double a, b, c, delta, x1, x2, m, n, i, j;
	scanf_s("%lf%lf%lf", &a, &b, &c);

	if (fabs(a) <= 1e-6) {                    //用来判断t是不是0,在C语言中|t|<1e-6,一般就认为t是0了
		if (fabs(b) <= 1e-6)
			puts("Not an equation");
		else
			printf("%.2lf", -c / b);
	}
	else {
		delta = b * b - 4 * a * c;
		m = -b / (2 * a);
		n = sqrt(fabs(delta)) / (2 * fabs(a));
		i = m + n;
		j = m - n;

		if (delta < 0)
		{
			printf("%.2lf+%.2lfi %.2lf-%.2lfi", m, n, m, n);
		}
		else 
		{
			if (i == j)
			{
				printf("%.2lf %.2lf", i, i);
			}
			else 
			{
				x1 = (i > j) ? i : j;
				x2 = (i > j) ? j : i;
				printf("%.2lf %.2lf", x1, x2);
			}
		}
	}
}
/*说明:
(1)如果a为0且b为0,则输出 “Not an equation”(N大写,单词间一个空格)。
(2)如果a为0,退化一次方程,则只输出一个根的值既可以。
(3)如果a不为0,则按以下格式输出方程的根x1和x2(x1和x2之间有一个空格):
* 若x1和x2为实根,则以x1>=x2输出。
* 若方程是共轭复根,则x1=m+ni,x2=m-ni,其中n>0。
其中x1、x2、m、n均保留2位小数。
提示(Hint):
(1)求平方根使用库函数sqrt(x),并需要 #include <math.h>
(2)保留2位小数使用printf("%.2f", … )
(3)输出i的方法如下:
printf("%0.2lf+%0.2lfi %0.2lf-%0.2lfi", 实部, 虚部, 实部, 虚部);
示例(Sample):
输入(Input):
1 2 3
输出(Output):
-1.00+1.41i -1.00-1.41i
说明:-1.00+1.41i -1.00-1.41i 两个根中间有一个空格*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值