如何在 C 中打印带有正确符号的方程式



基本上,我必须在所有数字上打印一个带有正确标牌的方程式。 我当前的代码是:

printf("%dx^2+%dx+%d=0", a, b, c);

考虑到我已经有了 a、b 和 c 的值,我希望这能起作用。但是,负数会搞砸这一点,因为如果我设置

a = 2, b = 2

, c = -2

(只是一个例子(,它将输出

2x^2+2+-2=0

这显然看起来不正确,那么我该如何设置它,以便如果它是负数,加号将不再存在?我唯一的想法是删除所有加号,但随后我会得到

2x^22-2=0

这也行不通。我知道这可能是一个简单的解决方案,但我是新手,任何帮助将不胜感激。谢谢。

您可以使用printf标志字符'+'轻松完成所需的输出。具体来自man 3 printf

标记字符

+      A sign (+ or -) should always be placed before a number produced
by  a  signed  conversion.   By default, a sign is used only for 
negative numbers.  A + overrides a space if both are used.

例如:

#include <stdio.h>
int main (void) {
int a = 2, b = 2, c = -2;
printf ("%dx^2%+dx%+d = 0n", a, b, c);
}

示例使用/输出

$ ./bin/printfsign
2x^2+2x-2 = 0

仔细看看,让我知道这是否是你的意图。

最新更新