尝试使用数组创建随机数生成器并获取标识符 "i" 是未定义的。任何人都可以看到问题吗?
Trying to create a random number generator using Arrays and getting Identifier "i" is Undefined. Can anyone see the problem?
尝试使用数组创建随机数生成器,但是“a[i] = rand();”我的部分代码产生了类型为“Identifier i is Undefined”的错误。谁能在这里找到我哪里出错了?谢谢
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main()
{
int a[10] = {};
for (int i = 0; i < size(a); i++); {
a[i] = rand();
}
for (int i = 0; i < size(a); i++) {
cout << "The random number is: " << a[i] << endl;
}
}
$ clang++-7 -pthread -std=c++17 -o main main.cpp
main.cpp:15:11: error: use of undeclared identifier 'i'
a[i] = rand();
^
main.cpp:13:38: warning: for loop has empty body
[-Wempty-body]
for (int i = 0; i < size(a); i++); {
^
main.cpp:13:38: note: put the semicolon on a separate line
to silence this warning
1 warning and 1 error generated.
compiler exit status 1
clang 有助于指出您在 for 循环后有一个意外的分号。
您的代码中的错误是一个杂散的分号。尝试学习像 gdb 这样的调试器,将有助于解决此类问题。 rand()
函数使用种子,srand()
用于change/set种子。
#include <iostream>
#include <string>
#include <array>
#include <ctime>. // Added for random seed generation
using namespace std;
int main()
{
int a[10] = {};
srand(time(0)); /* Added this to ensure seed of rand() is always different otherwise you might have ended up with same random numbers on different runs */
for (int i = 0; i < size(a); i++) { /*Issue was here, you had stray semicolon */
a[i] = rand();
}
for (int i = 0; i < size(a); i++) {
cout << "The random number is: " << a[i] << endl;
}
}
尝试使用数组创建随机数生成器,但是“a[i] = rand();”我的部分代码产生了类型为“Identifier i is Undefined”的错误。谁能在这里找到我哪里出错了?谢谢
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main()
{
int a[10] = {};
for (int i = 0; i < size(a); i++); {
a[i] = rand();
}
for (int i = 0; i < size(a); i++) {
cout << "The random number is: " << a[i] << endl;
}
}
$ clang++-7 -pthread -std=c++17 -o main main.cpp
main.cpp:15:11: error: use of undeclared identifier 'i'
a[i] = rand();
^
main.cpp:13:38: warning: for loop has empty body
[-Wempty-body]
for (int i = 0; i < size(a); i++); {
^
main.cpp:13:38: note: put the semicolon on a separate line
to silence this warning
1 warning and 1 error generated.
compiler exit status 1
clang 有助于指出您在 for 循环后有一个意外的分号。
您的代码中的错误是一个杂散的分号。尝试学习像 gdb 这样的调试器,将有助于解决此类问题。 rand()
函数使用种子,srand()
用于change/set种子。
#include <iostream>
#include <string>
#include <array>
#include <ctime>. // Added for random seed generation
using namespace std;
int main()
{
int a[10] = {};
srand(time(0)); /* Added this to ensure seed of rand() is always different otherwise you might have ended up with same random numbers on different runs */
for (int i = 0; i < size(a); i++) { /*Issue was here, you had stray semicolon */
a[i] = rand();
}
for (int i = 0; i < size(a); i++) {
cout << "The random number is: " << a[i] << endl;
}
}