【问题标题】:equation solver in C segmentation faultC分段错误中的方程求解器
【发布时间】:2013-06-27 14:49:08
【问题描述】:
#include <stdio.h>

int main()
{
  printf("choose number");
  c();
}

c()
{
  printf("1. ax+b=0\n\n");
  printf("2. ax+by+c=0\n   dx+ey+f=0\n\n");
  int n;

  scanf("%d", &n);

  if (n > 3)
    wrong();
  if (n == 1)
    formula1();
  if (n == 2)
    formula2();
  if (n == 3)
    ;
  formula3();
}

wrong()
{
  printf("Please choose a number between 1 and 3.\n\n");
  c();
}

formula1()
{
  printf("ax+b=0\n");
  printf("Enter your values for a and b respectively, seperated by commas\n");
  float a, b, x;
  scanf("%f,%f,%f", &a, &b);
  x = -b / a;
  printf("x=-b/a\n");
  printf("=>x=%f", x);
  question();
}

formula2()
{
  printf("ax+by+c=0\n\ndx+ey+f=0\n");
  printf(
      "Enter your values for a, b, c, d ,e and f respectively, seperated by commas\n");
  float a, b, c, d, e, f, x, y;
  scanf("%f,%f,%f,%f,%f,%f", &a, &b, &c, &d, &e, &f);
  x = ((f * b) - (c * e)) / ((a * e) - (d * b));
  y = ((c * d) - (f * a)) / ((e * a) - (d * b));
  printf("=>x=%f", x);
  printf("\n\n");
  printf("=>y=%f", y);
  question();
}

question()
{
  char t;
  printf("\n\nanother equation?\ny/n?\n");
  if (t == 'y')
  {
    printf("\n\n\n\n\n");
    c();
  }
  else if (t != 'n')
    question();
}

我有这段代码,简而言之,它可以解决 3 个方程。 当您选择任何选项时,它似乎多次运行问题方法然后由于segmentation fault: 11而退出

有人可以指出我哪里出错了。对我的代码的任何其他帮助将不胜感激

【问题讨论】:

  • scanf("%f,%f,%f",&amp;a, &amp;b); 你到底想在这里做什么?重要的是在这里检查x=-b/a; a != 0
  • 请稍微格式化(缩进)你的代码。
  • 你可能想编译所有警告(-Wall on gcc),修复代码直到不再出现警告,然后使用 valgrind 运行程序并修复代码直到不再出现警告,最后您可以随时回来提问(如果仍有必要)。

标签: c


【解决方案1】:

这里有一个问题:

scanf("%f,%f,%f",&a, &b);

这三个值只提供了两个参数。

【讨论】:

    【解决方案2】:

    question() 中没有像scanf() 这样的输入函数,因此如果t 偶然不是'y' 或'n',你会得到一个无限递归,直到堆栈大小被超出...

    【讨论】:

    • 那个,代码引用了一个名为choice的函数,该函数未包含在帖子中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    相关资源
    最近更新 更多