[英]Why am I getting the error “using uninitialized memory 'i'” and “uninitialized local variable 'i' used” when trying to make i = i*i
I am new to C++ and was testing out while
loops and the sheer speed of C++ and its toll on my CPU and I got the following errors:我是 C++ 的新手,正在测试
while
循环和 C++ 的绝对速度及其对我的 CPU 的影响,我收到以下错误:
Severity Code Description Project File Line Suppression State Warning C6001 Using uninitialized memory 'i'
Severity Code Description Project File Line Suppression State Error 4700 uninitialized local variable 'i' used
I have no idea how to read an error message and haven't even encountered initializing in C++ yet so I don't have any clue about what to do.我不知道如何阅读错误消息,甚至还没有遇到在 C++ 中的初始化,所以我不知道该怎么做。
#include <iostream>
using namespace std;
int main() {
long long i = 0;
while (i < 10000000000000000) {
long long i = i*i;
cout << i ;
}
cout << i;
return 0;
}
In the body of the while loop在 while 循环的主体中
while (i < 10000000000000000) {
long long i = i*i;
cout << i ;
}
you declared the variable i
that is not initialized and has an indeterminate value and you are trying to use this indeterminate value to initialize the variable itself.您声明了未初始化的变量
i
并且具有不确定的值,并且您正在尝试使用此不确定的值来初始化变量本身。
That is in this declaration就是在这个声明中
long long i = i*i;
in the initializer there is used the same declared variable i that hides the declaration of the variable with the same name that appears before the loop在初始化程序中,使用了相同的声明变量 i,它隐藏了在循环之前出现的同名变量的声明
Substitute the declaration for the statement用声明代替声明
i = i*i;
But initially you should set the variable i to some value unequal to 0 for example to 10.但最初您应该将变量 i 设置为不等于 0 的某个值,例如 10。
long long i = 10;
Otherwise the result of the expression i * i
always will be equal to 0.否则表达式
i * i
的结果总是等于 0。
Something like就像是
#include <iostream>
using namespace std;
int main() {
long long i = 10;
while (i < 10'000'000'000'000'000) {
i = i*i;
cout << i ;
}
cout << i;
return 0;
}
Though you should be caution selecting the initial value of the variable i
because an overflow can occur in the expression i * i
and you can get an infinite loop.尽管您应该谨慎选择变量
i
的初始值,因为表达式i * i
中可能会发生溢出,并且您会得到一个无限循环。
long long i = i * i;
shadows the long long i = 0;
阴影
long long i = 0;
declared outside the while loop.在 while 循环之外声明。 It's a totally separate variable and you're attempting to initialize it to its own value squared.
它是一个完全独立的变量,您正在尝试将其初始化为自己的平方值。 If you want to use the variable
i
you declared outside the loop, drop the redeclaration:如果要使用在循环外声明的变量
i
,请删除重新声明:
#include <iostream>
using namespace std;
int main() {
long long i = 0;
while (i < 10000000000000000) {
i = i*i;
cout << i ;
}
cout << i;
return 0;
}
Note that this will be an endless loop that just prints 0
over and over again.请注意,这将是一个无限循环,只会一遍又一遍地打印
0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.