c - 如何在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
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
看看事情,让我知道这是否是你的意图。
推荐阅读
- azure - 如何在 Azure DevOps 构建管道中配置外部 Nuget 源(包)
- maven - 使用多阶段关系存储库时是否可以排除工件被镜像
- blazor - BLAZOR:使用组件基类模型时自动触发 Onclick 事件
- qt - 如何将变量从 c++ 发送到 qml?你能给我发一个例子吗
- javascript - Reactive Streams 疯狂卡牌选择 sphagetti 动作
- dropzone.js - Dropzone问题:无法从文件上传中接收文件信息
- oracle - SSIS 提取(来自 OrAcle)包失败,出现以下错误
- javascript - 节点找不到在 tsconfig 和 package.json 中定义的模块别名
- json - 加入 mongodb 中的集合
- android-studio - 新 Activity:为什么 Android Studio 要为“Wear OS”创建一个空白 Activity?