C语言求ax+b=0 的解,a、b的值由键盘输入代码
时间: 2024-05-19 14:12:45 浏览: 15
#include <stdio.h>
int main() {
float a, b;
printf("请输入a和b的值:");
scanf("%f %f", &a, &b);
if (a == 0 && b == 0) {
printf("方程有无数解\n");
} else if (a == 0 && b != 0) {
printf("方程无解\n");
} else {
printf("方程的解为:%.2f\n", -b / a);
}
return 0;
}
相关问题
c语言求ax²+bx+c=0方程的根,其中a,b,c从键盘输入。
以下是c语言代码:
```c
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, x1, x2, discriminant;
printf("请输入a, b, c的值:");
scanf("%f %f %f", &a, &b, &c);
discriminant = b*b - 4*a*c;
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
printf("方程的两个根为:x1 = %.2f, x2 = %.2f", x1, x2);
}
else if (discriminant == 0) {
x1 = -b / (2*a);
printf("方程的根为:x1 = x2 = %.2f", x1);
}
else {
printf("方程无实根");
}
return 0;
}
```
首先,我们需要从键盘输入a、b、c的值。然后,我们计算判别式discriminant的值,用它来判断方程的根的情况。
如果判别式discriminant大于0,方程有两个不同的实根,我们可以使用求根公式计算出两个根x1和x2,并打印它们的值。
如果判别式discriminant等于0,方程有一个重根,我们可以使用求根公式计算出根x1,并将其打印两次。
如果判别式discriminant小于0,方程没有实根。我们只需打印"方程无实根"即可。
运用C语言解决求ax2+bx+c=0的根,a,b,c由键盘输入。最简单的代码
以下是解决ax^2 + bx + c = 0的根的C语言代码,a、b、c由键盘输入:
```
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, discriminant, root1, root2;
printf("请输入系数 a, b, c:\n");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
printf("方程无实根。\n");
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("方程有两个相等的实根:%lf\n", root1);
} else {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("方程有两个不同的实根:%lf 和 %lf\n", root1, root2);
}
return 0;
}
```
在该程序中,我们首先通过 `scanf` 函数从键盘获取输入的系数 a、b、c 的值,并计算出判别式 `discriminant`。接着,我们使用 `if` 和 `else if` 语句来判断方程是否有实根,如果没有则输出“方程无实根”,否则分别计算出方程的两个实根并输出。其中涉及到了平方根的运算,我们调用了 math.h 库中的 `sqrt` 函数进行计算。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)