gpt4 book ai didi

c - 如何在C中打印带有正确符号的等式

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:56 26 4
gpt4 key购买 nike

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

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:

Flag characters

+      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

检查一下,让我知道这是否是您想要的。

关于c - 如何在C中打印带有正确符号的等式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com