Вопрос задан 13.07.2023 в 20:34. Предмет Информатика. Спрашивает Панченко Даниил.

C++ 1. Дана программа, которая определяет последнее положительное и первое отрицательное число в

массиве. Найти и исправить синтаксические и логические ошибки, перечислив их. #include using namespace std; int main() { double size = 8; double arr[size]={-5.7, 6.0, 2, 0, -4.7, 6, 8.1, -4, 0}; int positive = 0; for (int i = size; i >= 0; i++) { if (arr[i] > 0) { positive = arr[i]; break; } } int negative = 0; for (int i = 0; i < size; i++) { if (arr[i] < 0) { negative = arr[i]; break; } } cout << "Last positive number: " << positive << endl; cout << "First negatine number: " << negative << endl; return 0; } ////////// Входными данными во всех описанных ниже заданиях является массив из 10 элементов, заполненный пользователем с клавиатуры.
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Русских Маша.

Ответ:

#include <iostream>

using namespace std;

int main()

{

//double size = 8;//необходима константа на целое число  

const int size = 8;

//double arr[size] = { -5.7, 6.0, 2, 0, -4.7, 6, 8.1, -4, 0 }; //лишнее число. Должно быть 8

double arr[size] = { -5.7, 6.0, 2, 0, -4.7, 6, 8.1, -4 };

//int positive = 0; //в массиве тип double, будет потеря данных если использовать int

double positive = 0;

//for (int i = size; i >= 0; i++)//если идем с конца, то нужно начинать с size-1, т.к. нумерация в массиве с нуля и i--, т.к. идем с конца

for (int i = size - 1; i >= 0; i--)

{

 if (arr[i] > 0)

 {

  positive = arr[i];

  break;

 }

}

//int negative = 0;//в массиве тип double, будет потеря данных если использовать int

double negative = 0;

for (int i = 0; i < size; i++)

{

 if (arr[i] < 0)

 {

  negative = arr[i];

  break;

 }

}

cout << "Last positive number: " << positive << endl;

cout << "First negatine number: " << negative << endl;

return 0;

}

Объяснение:

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Let's go through the code and identify the syntax and logic errors:

  1. Syntax Errors: a. #include is missing at the beginning of the code. It should be #include <iostream> to include the necessary library for input/output operations. b. The < and > symbols for comparison are encoded incorrectly as HTML entities (&gt; and &lt;). They should be replaced with the regular comparison operators (> and <).

  2. Logical Errors: a. The loop to find the last positive number is starting from size, which is an invalid index. Arrays in C++ are 0-indexed, so the loop should start from size - 1. b. The loop to find the first negative number is correct, but the initial value of negative should be set to a number that is guaranteed to be positive in the array. Initializing negative to 0 will cause incorrect results if the first element in the array is negative.

Here's the corrected code:

cpp
#include <iostream> using namespace std; int main() { const int size = 8; // Change to const int to use as array size double arr[size] = {-5.7, 6.0, 2, 0, -4.7, 6, 8.1, -4}; // Removed extra zero at the end double positive = 0; for (int i = size - 1; i >= 0; i--) { // Corrected the loop starting point if (arr[i] > 0) { positive = arr[i]; break; } } double negative = arr[0]; // Initialized to the first element in the array for (int i = 0; i < size; i++) { if (arr[i] < 0) { negative = arr[i]; break; } } cout << "Last positive number: " << positive << endl; cout << "First negative number: " << negative << endl; return 0; }

Now the code should work correctly and display the last positive number and the first negative number in the array.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос