如何用C中的正确符号打印方程式

问题描述 投票:1回答:1

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

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

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

c algorithm sign
1个回答
6
投票

您可以使用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 = 0\n", a, b, c);
}

示例使用/输出

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

看看事情,让我知道这是否是你的意图。

© www.soinside.com 2019 - 2024. All rights reserved.