在C中使用'%i'输入任何格式(十进制,八进制或十六进制)的整数值

We know that the decimal, octal, and hexadecimal value can be read through scanf() using "%d", "%o" and "%x" format specifier respectively.

我们知道,可以分别使用“%d” , “%o”和“%x”格式说明符通过scanf()读取十进制,八进制和十六进制值。

  • "%d" is used to input decimal value

    “%d”用于输入十进制值

  • "%o" is used to input integer value in an octal format

    “%o”用于以八进制格式输入整数值

  • "%x" is used to input integer value in hexadecimal format

    “%x”用于以十六进制格式输入整数值

But, there is the best way to read the integer value in any format from decimal, octal and hexadecimal - there is no need to use different format specifiers. We can use "%i" instead of using "%d", "%o" and "%x".

但是,最好的方法是从十进制,八进制和十六进制中读取任何格式的整数值-无需使用其他格式说明符。 我们可以使用“%i”代替“%d” , “%o”和“%x”

“%i”格式说明符 ("%i" format specifier)

It is used to read an integer value in decimal, octal or hexadecimal value.

用于读取十进制,八进制或十六进制值的整数值。

  • To input value in decimal format - just write the value in the decimal format, example: 255

    要以十进制格式输入值-只需以十进制格式输入值, 例如:255

  • To input value in octal format - just write the value in octal format followed by "0", example: 03377

    要以八进制格式输入值-只需以八进制格式写入值,后跟“ 0”即可例如:03377

  • To input value in hexadecimal format – just write the value in hexadecimal format followed by "0x", example: 0xff

    要以十六进制格式输入值–只需以十六进制格式写入值,后跟“ 0x”即可例如:0xff

Program:

程序:

#include <stdio.h>

int main(void)
{
	int num;
	
	printf("Enter value: ");
	scanf("%i", &num);
	printf("num = %d\n", num);
	
	return 0;
}

Output

输出量

Run1: Reading value in decimal format
Enter value: 255
num = 255

Run2: Reading value in octal format
Enter value: 0377
num = 255 

Run3: Reading value in hexadecimal format
Enter value: 0xFF
num = 255 


翻译自: https://www.includehelp.com/c-programs/input-an-integer-value-in-any-format-decimal-octal-or-hexadecimal.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值