Форум программистов, компьютерный форум, киберфорум
C/С++ под Linux
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 27.09.2021
Сообщений: 18

Из массива выходят странные числа

18.04.2023, 18:10. Показов 918. Ответов 0

Студворк — интернет-сервис помощи студентам
Здравствуйте у меня проблема, при создании массива генерируются правильные числа, а при взятии этих чисел в другой файл выводится всякая фигня.
613228528 32765 88615552
-2029537266 0 35397344
-613228464 32765 88717360
-613228480 32765 90551144
-613228528 0 3
-2029537266 0 90551144
-613228312 32765 88819029
-613228464 32765 90677745
-1 0 90556176
-1 0 32
-25761258 0 88615984
Помогите пожалуйста исправить, вот мой код:

#include <iostream>
#include <vector>
#include <fstream>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
void generate_array (std::string file_name_arr , int max_num){
std::ofstream out {file_name_arr};
for (int i= 0; i < 5; ++i) {
for (int j = 0; j < 100; ++j) {
out << rand() % (max_num + 1) << " ";
}
out << std::endl;
}
out.close();
}
void search_follow_ascending (std::string file_name_arr, std ::string file_name_result, int i_arr){
std::ifstream in {file_name_arr};
int arr [5][100];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 100; ++j) {
in >> arr[i][i];
}
}
in.close();
std::vector<std::vector<int>> follow_ascending;
for (int j = 1, i_vector{0}; j < 100; ++j) {
if (arr[i_arr][j] > arr[i_arr][j - 1]){
if (follow_ascending.size() == i_vector){
std::vector<int> temp;
follow_ascending. push_back(temp);
follow_ascending[i_vector] .push_back(arr[i_arr][j -1]);
}
follow_ascending[i_vector ].push_back(arr[i_arr][j]);
if (arr[i_arr][j + 1] < arr[i_arr][j])
i_vector++;
}
}
int max_elem_in_vector {0};
for (int i = 0; i < follow_ascending.size(); ++i) {
if (follow_ascending[i].size() > max_elem_in_vector)
max_elem_in_vector = follow_ascending[i].size();
}
std::ofstream out {file_name_result};
for (int i = 0; i < follow_ascending.size(); ++i) {
if(follow_ascending[i].size() == max_elem_in_vector){
for (int j = 0; j < follow_ascending[i].size(); ++j) {
out << follow_ascending[i][j] << " ";
}
out << std::endl;
}
}
out.close();
}
void search_descending_ascending (std::string file_name_arr, std::string file_name_result, int i_arr){
srand(time(0));
std::ifstream in {file_name_arr};
int arr [5][100];
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 100; ++j) {
in >> arr[i][j];
}
}
std::vector<std::vector<int>> descending_ascending;
for (int j = 1, i_vector{0}; j < 100; ++j) {
if (arr[i_arr][j] < arr[i_arr][j - 1]){
if (descending_ascending.size() == i_vector){
std::vector<int> temp;
descending_ascending.push_back(temp);
descending_ascending[i_vector ].push_back(arr[i_arr][j - 1]);
}
descending_ascending[i_vector ].push_back(arr[i_arr][j]);
if (arr[i_arr][j + 1] > arr[i_arr][j])
i_vector++;
}
}
int max_elem_in_vector {0};
for (int i = 0; i < descending_ascending.size(); ++i) {
if (descending_ascending[i].size() > max_elem_in_vector)
max_elem_in_vector = descending_ascending[i].size();
}
std::ofstream out {file_name_result};
for (int i = 0; i < descending_ascending.size(); ++i) {
if(descending_ascending[i].size() == max_elem_in_vector){
for (int j = 0; j < descending_ascending[i].size(); ++j) {
out << descending_ascending[i][j] << " ";
}
out << std::endl;
}
}
out.close();
}

int main() {
srand(time(0));
generate_array("array.txt", 100);
pid_t pid1;
pid1=fork();
if (pid1 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid1 == 0){
std::cout << "this is child process 1. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "follow_ascending_1.txt", 0);
exit(0);
}
pid_t pid2;
pid2=fork();
if (pid2 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid2 == 0){
std::cout << "this is child process 2. my pid " << getpid() << std::endl;
search_follow_ascending("array.txt", "descending_ascending_1.txt", 0);
exit(0);
}
pid_t pid3;
pid3=fork();
if (pid3 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid3 == 0){
std::cout << "this is child process 3. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "follow_ascending_2.txt", 1);
exit(0);
}
pid_t pid4;
pid4=fork();
if (pid4 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid4 == 0){
std::cout << "this is child process 4. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "descending_ascending_2.txt", 1);
exit(0);
}
pid_t pid5;
pid5=fork();
if (pid5 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid5 == 0){
std::cout << "this is child process 5. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "follow_ascending_3.txt", 2);
exit(0);
}
pid_t pid6;
pid6=fork();
if (pid6 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid6 == 0){
std::cout << "this is child process 6. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "descending_ascending_3.txt", 2);
exit(0);
}
pid_t pid7;
pid7=fork();
if (pid7 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid7 == 0){
std::cout << "this is child process 7. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "follow_ascending_4.txt", 3);
exit(0);
}
pid_t pid8;
pid8=fork();
if (pid8 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid8 == 0){
std::cout << "this is child process 8. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "descending_ascending_4.txt", 3);
exit(0);
}
pid_t pid9;
pid9=fork();
if (pid9 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid9 == 0){
std::cout << "this is child process 9. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "follow_ascending_5.txt", 4);
exit(0);
}
pid_t pid10;
pid10=fork();
if (pid10 < 0){
std::cout << "Cannot create child process.Exit!!!" << std::endl;
exit(1);}
else if (pid10 == 0){
std::cout << "this is child process 10. my pid " << getpid()<<std::endl;
search_follow_ascending("array.txt", "descending_ascending_5.txt", 4);
exit(0);
}
else {
std::cout << "This is parents process. ID: "<< getppid()<< std::endl;}
return 0;
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
18.04.2023, 18:10
Ответы с готовыми решениями:

Выводятся странные числа в качестве элементов массива
Программа считает 100 событий, в результате чего получаем массив из 100 чисел типа double, который выводится в файл. Затем эти числа...

Из массива выходят странные числа
Здравствуйте у меня проблема, при создании массива генерируются правильные числа, а при взятии этих чисел в другой файл выводится всякая...

Выводятся странные числа в качестве элементов массива
Есть массив MM из чисел типа float, нужно его построить частотную гистограмму из элементов массива, для этого используется следующий цикл: ...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
18.04.2023, 18:10
Помогаю со студенческими работами здесь

Почему по итогу выходят не те числа?
Console.WriteLine(&quot;Введите число&quot;); int b = Convert.ToInt32(Console.ReadLine()); int a = new int {33, 42, 65, 23, 22}; foreach (int i...

Не выходят значения массива на экран
var myObj, i, j, x = &quot;&quot;; myObj = { &quot;name&quot;:&quot;John&quot;, &quot;age&quot;:30, &quot;cars&quot;: }, { &quot;name&quot;:&quot;BMW&quot;, &quot;models&quot;: }, ...

Вывод массива: выходят нули и одно число
Новичок в Java. Задача была - создать массив из всех нечётных чисел от 1 до 99, вывести его на экран в строку, а затем этот же массив...

Найти номера элементов массива, значения которых выходят за пределы интервала
1)Ввод значений элеметов массива из N элементов и вывод массива на экран монитора. 2)В числовом ряду из Т элементов найти номера...

Странные числа
print(a ** b, b ** a) 243 125 Задание узнать значение a и b


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru