Уроки C++
Рандомный массив в С++В этом уроке вы познакомитесь с разными видами рандомного массива. Есть такая “волшебная” строка - rand(). Виды рандомных одномерных, двумерных и прочих массивов можно разделить на следующие: все числа от 1 до 10; все числа от 1 до 100 ну и более, хоть 100500 :) числа от -10 до 10 или -100 до 100 и т.д; массив из вещественных чисел; Сейчас вы узнаете, как выводить каждый из них. В этом уроке будем выводить одномерные массивы, в следующем уроке рассмотрим двумерные. Создайте приложение Win32 подключите библиотеку - #include "time.h" и напечатайте следующие коды:              все числа от 1 до 10 (или 100):
#include "stdafx.h" #include "clocale" #include "time.h" #include "iostream" using namespace std; int main() { setlocale(LC_ALL, "Russian" ); const int n = 12;   // фиксированное число элемнтов int a[n]; srand(time(NULL)); cout << "Массив: "; for (int i=0; i<n; i++) { a[i]=rand()%10;   // или a[i]=rand()%100; cout << a[i] << " "; } cout <<"\r\n"; system("PAUSE"); return 0; }
Результат:

#include "stdafx.h" #include "clocale" #include "time.h" #include "iostream" using namespace std; int main() { setlocale(LC_ALL, "Russian" ); const int n = 12;   // фиксированное число элемнтов int a[n]; srand(time(NULL)); cout << "Массив: "; for (int i=0;i<n;i++) { a[i]=rand()%(0+10);   // просто приписываем 0+ cout << a[i] << " "; } cout <<"\r\n"; cout <<"\r\n"; system("PAUSE"); return 0; }
Результат:

#include "stdafx.h" #include "clocale" #include "time.h" #include "iostream" using namespace std; int main() { setlocale(LC_ALL, "Russian" ); cconst int n = 18; int a[n]; srand(time(NULL)); cout << "Массив: "; for (int i=0;i<n;i++) { a[i]=rand()%20-10;   // или a[i]=rand()%200-100; cout << a[i] << " "; } cout <<"\r\n"; cout <<"\r\n"; system("PAUSE"); return 0; }
Результат:

#include "stdafx.h" #include "clocale" #include "time.h" #include "iostream" using namespace std; int main() { setlocale(LC_ALL, "Russian" ); cconst int n = 18; int a[n]; srand(time(NULL)); cout << "Массив: "; for (int i=0;i<n;i++) { a[i]=(10+10)*(double)rand()/ RAND_MAX-10;   // или "+" cout << a[i] << "\r\n";   //a[i]=(10+10)*(double)rand()/RAND_MAX+10 } cout <<"\r\n"; cout <<"\r\n"; system("PAUSE"); return 0; }
Результат:
