c - 如何通过 Scanf 将二次方程作为输入?
问题描述
我正在学习 C 的课程,我被要求找到一个二次方程的根。首先我尝试了硬编码并且它奏效了。接下来我使用scanf(如a,b,c)给出输入,它起作用了。但是在将整个二次表达式作为输入即 (ax^2+bx+c) 并从表达式中检索这些 a、b、c 值的情况下,我失败了。我花了很多时间在网上搜索我找不到答案所以我在这里寻求帮助。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define PI 3.14
int main(void)
{
puts("---- ROOTS ----");
char equ[20]; //Quadratic Expression in an Array
float a,b,c,ope;
float root1,root2;
printf("please provide the expression :");
scanf("%d",&equ[20]);//Example : 5x^2+3x+1 as input
a == equ[0];//since ax^2+bx+c in the above expression a==5
b == equ[3];//b==3
c == equ[6];//c==1
ope = sqrt(b*b -4*a*c);
root1 = (-b + ope)/2*a;
root2 = (-b - ope)/2*a;
printf("The root 1 of the expression is : %d", root1);
printf("\nThe root 2 of the expression is : %d", root2);
return EXIT_SUCCESS;
}
输出 :
PS F:\Thousand C GO> gcc 3.c
PS F:\Thousand C GO> ./a
---- ROOTS ----
please provide the expression :5x^2+3x+1//edited
The root 1 of the expression is : 0
The root 2 of the expression is : 0
我想知道是否有办法在 C 中解决这个问题,如果有怎么办?如果不是为什么?
非常感谢您的帮助。谢谢。
解决方案
- 要读取字符串 -
尝试
scanf("%s",equ);
或者
scanf("%s",&equ[0]);
== 是“等于”运算符。您可能希望将其更改为 =(赋值运算符)
重新检查您用于提取二次方程中的系数的索引值。
Coefficients are stored in ascii values in the character array. You need to convert them to appropriate integer or numeric value.
推荐阅读
- python-3.x - 查找和替换 xml 子标签文本的 Python 代码
- javascript - 即使在成功的承诺回调之后,组件道具也是空的 - 角度测试
- azure - 90 天后访问 Azure B2C 登录日志
- javascript - 您必须将组件传递给 connect 返回的函数。而是收到 {"propTypes":{}}
- php - 如何将变量从 foreach 循环发送到数组?
- c# - Visual Studio:弹出窗口以显示已实现的接口
- ag-grid - 无法在 stencil.js 中为 ag-grid 进行基本设置
- selenium - Selenium(日期选择器问题)
- html - mailto链接打开无限数量的新标签
- dataframe - 如何复制文件第一行中的每个单词