config = configparser.ConfigParser()
config.read('config.ini')
config['Categorie']['new_variable'] = variable
with open('config.ini', 'w') as configfile:
config.write(configfile)
请帮助我为什么myArray []结果为1436189223
答案 0 :(得分:2)
让我们逐步进行介绍(这也是您在调试器中可以执行的操作!):
int[]myArray = new int[5];
:这将是一个数组{0,0,0,0,0}
。大小为5的数组,默认值为int
-值0
。
for(int index=0; index<myArray.length; index++)
:在[0, 5)
范围内循环:
myArray[3] = 100*myArray[3]*myArray[3]+3;
:让我们将其分为以下几个子步骤:
myArray[3] = 100 * 0 * 0 + 3
产生3
myArray[3] = 100 * 3 * 3 + 3
产生903
myArray[3] = 100 * 903 * 903 + 3
产生81540903
myArray[3] = 100 * 81540903 * 81540903 + 3
产生-749594073
myArray[3] = 100 * -749594073 * -749594073 + 3
产生1436189223
System.out.println("myArray[]="+myArray[3]);
:打印myArray[3]
的值,即1436189223
。
一些注意事项。首先,为什么要使用myArray[3]
开始。这将是一个更简单的选择,因为您根本不使用数组:
int result=0;
for(int i=0; i<5; i++)
result = 100*result*result+3;
System.out.println("Result: "+result);
但是您的问题可能主要是关于100 * 81540903 * 81540903 + 3
为何产生-749594073
的问题。这是因为最大int
大小是2 32 -1(2,147,483,647
)。之后,它将环绕。因此int i = 2147483647 + 1
将产生-21474836481
(或更常见的是Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
)。
同样适用于其他数据类型,例如byte
,short
,long
等。Here you can see some of those ranges per data type.
由于long
是64位而不是int
的32位,因此可以在此处使用它来获得正确的结果:
long result=0L;
for(int i=0; i<5; i++)
result = 100*result*result+3;
System.out.println("Result: "+result);
或使用您的原始代码:
long[]myArray = new long[5]; // <- This is a long-array now
for(int index =0;index<myArray.length;index++)
myArray[3]=100*myArray[3]*myArray[3]+3;
System.out.println("myArray[]="+myArray[3]);
PS:如果必须超出long
的大小,则必须使用java.math.BigInteger
。
答案 1 :(得分:1)
实际上非常简单,您的循环运行5次。在每次迭代中,它使用myArray[3]
的先前值,计算新值,然后将该值存储在同一索引中。
何时:-
index = 0; myArray [3] = 3
index = 1; myArray [3] = 903
index = 2; myArray [3] = 81540903
index = 3; myArray [3] = -749594073
index = 4; myArray [3] = 1436189223
另外,请注意,由于您没有在for-loop
周围使用方括号,因此它仅将下一行视为循环的一部分。