我在mac上尝试了以下代码,输出对我来说有点奇怪.
float a = 2.225;
float b = 123.235;
printf("round: %.2f %.2f \n", a, b);
printf("round: %.2f %.2f \n", 2.225, 123.235);
Run Code Online (Sandbox Code Playgroud)
输出:
round: 2.22 123.24
round: 2.23 123.23
Run Code Online (Sandbox Code Playgroud)
g ++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Run Code Online (Sandbox Code Playgroud)
印刷中的舍入规则是什么?如何在这两种情况下获得相同的打印效果?非常感谢.
据我所知,参数的格式说明符太少被认为是未定义的行为(格式说明符的参数太少也是未定义的行为).这适用于:
printf("%1$d %1$d", 5);
Run Code Online (Sandbox Code Playgroud)
PS使用"%1$d"as格式说明符是POSIX添加的函数族的扩展printf.
我正在学习编程C.你能解释一下这里为什么没有打印出来吗 提前致谢.
#include <stdio.h>
int main (void)
{
char a[]="abcde";
printf ("%s", a);
}
Run Code Online (Sandbox Code Playgroud) 我在RedHat中使用gdb来调试C++代码.为了更好地调试我的代码,我补充道printf("XXX").
但是,执行后printf("XXX"),gdb控制台没有显示XXX.
我的代码的其他部分工作正常.
如何以十进制表示法打印指针?
编译时,以下都不会产生所需的结果-Wall.我理解错误,并希望编译-Wall.但是,如何以十进制表示法打印指针?
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
printf("%p\n", ptr); // Hexadecimal notation
printf("%u\n", ptr); // -Wformat: %u expects unsigned int, has int *
printf("%u\n", (unsigned int) ptr); // -Wpointer-to-int-cast
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
(这是必需的,因为我在点图中使用指针作为节点标识符,并且0x..不是有效的标识符.)
这个小代码是UB吗?
void Test()
{
int bar;
printf("%p", &bar);
}
Run Code Online (Sandbox Code Playgroud)
IMO不是UB,但我想要其他一些意见.
bar即使bar从未初始化,它也只是打印地址.
我只花了一个划时代搞清楚,我的大整数是个好人,是printf的%d/ %u不可达显示它的任务:
use strict;
use warnings;
use bigint;
use List::Gen;
*factorial = do {use bigint; <[..*] 1, 1..>->code};
my $value = factorial(32);
printf "%d\n", $value; # -1
printf "%u\n", $value; # 18446744073709551615
printf "%s\n", $value; # 263130836933693530167218012160000000
Run Code Online (Sandbox Code Playgroud)
如果答案是否定的话,我不会感到惊讶,只是想确认一下.
我想为8号获得"0x08",但是当我使用"%#02x"时,我只得到0x8:
int i = 0x08;
printf("%#02x", i); // only print 0x8, not 0x08
Run Code Online (Sandbox Code Playgroud)
在格式字符串中的"#"后,宽度数似乎无法工作.除了使用"0x%02x"之外,有没有更好的方法来打印我想要的内容?
为了使我的代码可移植,我尝试使用printf而不是echo.但是之后
printf "-dogs-cats"
Run Code Online (Sandbox Code Playgroud)
返回错误.本案的解决方法是:
printf "-";printf "dogs-cats"
Run Code Online (Sandbox Code Playgroud)
但是有一个通用的,可移植的命令(或一个选项printf),它将打印任意字符串作为文字/逐字,而不是尝试将字符串解释为格式?
我在BSD UNIX(在Mac上)工作,但我的目标是在其他UNIX风格中也可以使用的代码.
我目前正在学习printflibc 的功能,但我不了解,两者之间有什么区别:
printf("Test : %010d", 10);
Run Code Online (Sandbox Code Playgroud)
使用0标志和10宽度说明符
和
printf("Test : %.10d", 10);
Run Code Online (Sandbox Code Playgroud)
采用10精密符
产生相同的输出: Test : 0000000010