首页 > 解决方案 > 如何通过 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 中解决这个问题,如果有怎么办?如果不是为什么?

非常感谢您的帮助。谢谢。

标签: carraysscanf

解决方案


  1. 要读取字符串 -

尝试

scanf("%s",equ);

或者

scanf("%s",&equ[0]);
  1. == 是“等于”运算符。您可能希望将其更改为 =(赋值运算符)

  2. 重新检查您用于提取二次方程中的系数的索引值。

  3. Coefficients are stored in ascii values in the character array. You need to convert them to appropriate integer or numeric value.


推荐阅读