C //习题 2.4(8) 求方程式ax^2 + bx + c = 0的根。

C语言设计 (第四版) 谭浩强 习题2.4(8)

习题 2.4(8) 求方程式 a x 2 + b x + c = 0 ax^2 + bx + c = 0 ax2+bx+c=0的根。

一元二次方程的根有三种情况:

  1. 有两个不等的实根;
  2. 有两个相等的实根;
  3. 无解。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。

 

代码块
方法1:使用条件语句
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(){
	int a, b, c, delta;
	double x1, x2;
	scanf_s("%d %d %d", &a, &b, &c);
	delta = b * b - 4 * a * c;
	if(delta > 0){
		x1 = (double)((-1) * b + sqrt((double)delta)) / 2 * a;
		x2 = (double)((-1) * b - sqrt((double)delta)) / 2 * a;
		printf("x1 = %.2f, x2 = %.2f\n", x1, x2);
	}
	else if(delta == 0){
		x1 = x2 = (-1) * b / 2 * a;
		printf("x1 = x2 = %.2f\n", x1);
	}
	else{
		printf("The equation has no solution!\n");
	}
	system("pause");
	return 0;
}
方法2:使用switch语句、指针、函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//输入函数
void input(int *arr, int size){
	for(int i = 0; i < size; i++){
		scanf_s("%d", &arr[i]);
	}
}

//判别式函数
int discriminant(int *arr){
	arr[3] = arr[1] * arr[1] - 4 * arr[0] * arr[2];
	if(arr[3] > 0){
		return 1;
	}
	else if(arr[3] == 0){
		return 0;
	}
	else{
		return -1;
	}
}

//求解方程函数
void equationOutput(int *arr){
	double x1, x2;
	switch(discriminant(arr)){
	case 0:
		x1 = x2 = (-1) * arr[1] / 2 * arr[0];
		printf("x1 = x2 = %.2f\n", x1);
		break;
	case 1:
		x1 = (double)((-1) * arr[1] + sqrt((double)arr[3])) / 2 * arr[0];
		x2 = (double)((-1) * arr[1] - sqrt((double)arr[3])) / 2 * arr[0];
		printf("x1 = %.2f, x2 = %.2f\n", x1, x2);
		break;
	default:
		printf("The equation has no solution!\n");
		break;
	}
}

int main(){
	//分配数组,其中arr[0]代表系数a,arr[1]代表系数b,arr[2]代表系数c,arr[3]用于存储判别式结果。
	int *arr = (int*)malloc(4 * sizeof(int));
	input(arr, 3);
	equationOutput(arr);
	free(arr);
	system("pause");
	return 0;
}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值