用相同的数字初始化c中的数组会导致不同的值 [英] Initializing an array in c with same numbers leads to different values

查看:51
本文介绍了用相同的数字初始化c中的数组会导致不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h> 
int main () {

int n[ 10 ] = {002535}; /* n is an array of 10 integers */
int j;

/* output each array element's value */
for (j = 0; j < 10; j++ ) {
  printf("Element[%d] = %d\n", j, n[j] );
}

return 0;
}

上面的代码运行并返回第一个等于1373的元素。你解释这个吗?我无法理解由于填充整数而更改数字背后的原因。

The above code runs and returns the first element to be equal to 1373. Could you explain this? I am not able to understand the reason behind the number being changed due to padding in the integer provided.

输出结果显示为以下几行。

Output comes out to be the following lines.

Element[0] = 1373
Element[1] = 0
...
Element[9] = 0


推荐答案

在您的程序中,您正在初始化数组 n -

In your program, you are initializing the array n -

int n[ 10 ] = {002535};

由于前导零,数字002535被解释为八进制数字。
因此,这会将八进制 002535 分配给 n [0] 即数组 n 中的第0个位置,其余数组元素将使用 0 初始化。

The number 002535 is interpreted as a octal number because of leading zeros. So, this will assign the octal value 002535 to n[0] i.e. 0th location in your array n and rest of array elements will be initialized with 0.

for 循环中,您使用格式说明符%d 进行打印。

In for loop, you are printing it with format specifier %d.

十进制值002535的十进制等效值为1373。这就是为什么将 Element [0] 用作1373的原因。

The decimal equivalent of 002535 octal value is 1373. That's why you are getting Element [0] as 1373.

如果要输出八进制数作为输出,请使用%o 格式说明符:

If you want to print octal number as output, use %o format specifier:

for (j = 0; j < 10; j++ ) {
  printf("Element[%d] = %o\n", j, n[j] );

如果想将小数点2535作为数组 n的第一个元素,删除前导零:

And if you want the decimal 2535 as first element of array n, remove leading zeros:

int n[ 10 ] = {2535};

这篇关于用相同的数字初始化c中的数组会导致不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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