0

这是我正在尝试修复的程序。我输入了 1,5,6,应该有 2 个解决方案,它说只有 1 个解决方案存在。我也试图让它显示十进制值(我应该使用双精度值吗?)。下面是我的代码,我做错了什么?

#include <stdio.h>
#include <math.h>

int main(void)
{
    int inputs[3], a, b, c, d, x, x1, x2, i, lastDigit;
    char *os, *noSol = "No solution\n", *cont = 'y';

    while (cont == 'Y' || cont == 'y')
    {
        printf("This program solves a quadratic equation\n");
        for (i = 1; i <= 3; i++)
        {

            lastDigit = i % 10;
            if (i >= 4 && i <= 20)
                os = "th";
            if (i == 1 || lastDigit == 1)
                os = "st";
            else if (i == 2 || lastDigit == 2)
                os = "nd";
            else if (i == 3 || lastDigit == 3)
                os = "rd";
            else
                os = "th";


            printf("Enter your %d%s number: ", i, os);
            scanf("%d", &inputs[i - 1]);
        }

        a = inputs[0];
        b = inputs[1];
        c = inputs[2];

        while (1)
        {
            if (a == 0)
            {
                if (b == 0)
                {
                    printf(noSol);
                    break;
                }
                else
                {
                    x = -c / b;
                    printf("The equation is not quadratic and the solution is %d\n", x);
                    break;
                }
            }
            else
            {
                d = pow(b, 2) - 4 * a * c;
                if (d < 0)
                {
                    printf(noSol);
                    break;
                }
                else if (d == 0)
                {
                    x1 = -b / 2 * a;
                    printf("One solution: %d\n", x1);
                    break;
                }
                else  if (d > 0)
                {
                    x1 = (-b + sqrt(d)) / 2 * a;
                    x2 = (-b - sqrt(d)) / 2 * a;
                    printf("Two solutions: %d and %d\n", x1, x2);
                    break;
                }
            }
        }

        printf("Run program second time? ( Y / N )\n");
        scanf("%s", &cont);
    }
    getch();
  }
4

1 回答 1

3

很多问题

  1. 数学部分应该使用double(or float) 而不是int.

    double inputs[3], a, b, c, d, x, x1, x2;

  2. printf()&scanf()对于双精度,格式说明符需要从%dto %le(或类似)更改为 match double

  3. 数学错误:在 3 个地方,/ 2 * a;应该是/ (2 * a);

  4. char *cont = 'y'应该char cont[2] = "y"

  5. scanf("%s", &cont);应该是scanf("%1s", cont);

  6. scanf()错误处理:应检查的返回值,如

    if (1 != scanf("%lf", &inputs[i - 1])) { ; /* Handle error */ }

  7. 小数学:if (d == 0)案例导致“双根”,而不是单一解决方案。实际上,考虑到浮点数学舍入,人们并不总是知道d在数学上应该完全为零,因此“单个”根实际上是 2 个非常接近的根。此外,使用选择值,“两个解决方案”将具有相同的值,应该sqrt(d)远小于b.

于 2013-09-24T22:47:43.983 回答