[英]Trying to create a random number generator using Arrays and getting Identifier "i" is Undefined. Can anyone see the problem?
嘗試使用數組創建隨機數生成器,但“ a[i] = rand() ;” 我的代碼的一部分創建了“標識符 i 未定義”類型的錯誤。 誰能找到我在這里出錯的地方? 謝謝
#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()
用於更改/設置種子。
#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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.