为什么 %d 代表整数? [英] why does %d stand for Integer?

查看:18
本文介绍了为什么 %d 代表整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这听起来并不高效,但我正在寻找一种方法来记住 printf 调用的所有格式代码.%s, %p, %f 都是显而易见的,但是我不明白 %d 是从哪里来的从.%i 是否已经被其他东西占用了?

I know this doesn't sound productive, but I'm looking for a way to remember all of the formatting codes for printf calls. %s, %p, %f are all obvious, but I can't understand where %d comes from. Is %i already taken by something else?

推荐答案

它代表十进制"(以 10 为底)),而不是整数".您可以使用 %xhexadecimal (base 16) 和 % 打印o八进制 (base 8) 打印.整数可以是这些基数中的任何一个.

It stands for "decimal" (base 10), not "integer." You can use %x to print in hexadecimal (base 16), and %o to print in octal (base 8). An integer could be in any of these bases.

printf() 中,您可以使用 %i 作为 %d 的同义词,如果您更愿意使用整数"来代替十进制",但通常首选 %d,因为它更具体.

In printf(), you can use %i as a synonym for %d, if you prefer to indicate "integer" instead of "decimal," but %d is generally preferred as it's more specific.

在输入时,使用 scanf(),您也可以同时使用 %i%d.%i 表示将其解析为任何基数的整数(八进制、十六进制或十进制,如 00x 前缀所示),而 %d 表示将其解析为十进制整数.

On input, using scanf(), you can use use both %i and %d as well. %i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.

以下是所有这些方法的示例:

Here's an example of all of them in action:

#include <stdio.h>

int main() {
  int out = 10;
  int in[4];

  printf("%d %i %x %o
", out, out, out, out);
  sscanf("010 010 010 010", "%d %i %x %o", &in[0], &in[1], &in[2], &in[3]);
  printf("%d %d %d %d
", in[0], in[1], in[2], in[3]);
  sscanf("0x10 10 010", "%i %i %i", &in[0], &in[1], &in[2]);
  printf("%d %d %d
", in[0], in[1], in[2]);

  return 0;
}

因此,如果您希望输入基数依赖于前缀,则应仅使用 %i;如果要固定输入基数,则应使用 %d%x%o.特别是,前导 0 将您置于八进制模式这一事实可以赶上您.

So, you should only use %i if you want the input base to depend on the prefix; if the input base should be fixed, you should use %d, %x, or %o. In particular, the fact that a leading 0 puts you in octal mode can catch you up.

这篇关于为什么 %d 代表整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆