首页 > 解决方案 > 如何在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

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

标签: calgorithmsign

解决方案


您可以使用printf flag character '+'轻松完成所需的输出。具体来自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

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


推荐阅读