A
A
Anya Frolova2020-10-06 00:25:28
C++ / C#
Anya Frolova, 2020-10-06 00:25:28

Processing one-dimensional arrays, how to modify the code?

Hello, help me, I can't deal with arrays.

What is: We enter 10 random numbers, after the program finds and shows the last positive number in the typed list. If there are no numbers, a message is displayed that there are none.

The code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace massiv
{
    class Program
    {
        static void Main(string[] args)
        {
            uint i = 0;
            double[] m = new double[10];
            bool q = false;

            Console.WriteLine("Введите 10 элементов массива:");

            do
            {
                Console.Write(" № "+(i+1)+": = ");
                m[i] = Convert.ToDouble(Console.ReadLine());
                i++;
            }
            while (i < 10);

            for (i = 0; i < 10; i++)
            {
                if (m[i] > 0)
                {
                    Console.Write("Последнее положительное число в массиве - " + m[i] + " имеет номер - "+(i+1));
                    q = true;
                    break;
                }
            }

            if (q == false) { Console.Write("Нет положительных чисел"); }

            Console.ReadLine();
        }
    }
}


Question: how to determine and display the value of the last positive element in order?

Answer the question

In order to leave comments, you need to log in

7 answer(s)
O
one pavel, 2020-10-06
@onepavel

almost correctly,
only you start looking from the zero element and at the first found you break the cycle,
and the task is the last, on the contrary, it means you need to bypass the array from the end
something like this for (i = 9; i < 0; i--)

S
Spark108, 2020-10-06
@spark108

Daria Motorina's method is quite working, and one pavel 's method is closer to your implementation, but I will still offer my code.

uint i = 0; 
 double[] m = new double[10]; 
 Console.WriteLine("Введите {0} значений:", m.Length); 

 do 
 { 
 Console.Write("{0}: ", i + 1); 
 m[i] = Convert.ToDouble(Console.ReadLine()); 
 i++; 
 } 
 while (i < m.Length); 

 int j = Array.FindLastIndex(m, (double d) => d > 0); 
 Console.WriteLine("Последнее положительное число в массиве - {0} имеет номер - {1}.", m[j], j+1);

We create an array in the same way as you do, and then you can use the Array.FindLastIndex method by passing the array itself as the first element, and the search condition as the second. The method will find the last element greater than zero and return its position in the array. By this position number, you can already request the number itself from the array and use it in your output.

C
cicatrix, 2020-10-07
@cicatrix

Why cut 2 passes? You can immediately determine at the input stage whether it is positive or not.
Well, Convert.ToDouble is bad practice. Better Double.TryParse

Console.WriteLine("Введите 10 элементов массива:");
double[] m = new double[10];
int lastPositive = -1;
for (int i = 0; i < 10; ++i)
{
    
   bool validate = false; // Флаг правильного ввода пользователя
   while (!validate)
   {
      Console.Write($"№ {i}:");
      validate = double.TryParse(Console.ReadLine(), out m[i]); // Вернёт false если пользователь ввёл фигню
   }
   if (m[i]  > 0) lastPositive = i;
}
if (-1 == lastPositive) Console.WriteLine("Положительных чисел не вводилось");
else 
Console.WriteLine($"Последнее положительное число имеет индекс {lastPotitive}");

D
Daria Motorina, 2020-10-06
@glaphire

Now, according to your logic, it goes like this - in the for loop, you iterate over the array, as soon as you meet a positive number - display the text and exit the for, i.e. it's actually the first positive number, not the last.
To find the latter, you need to create an intermediate empty array, go through the array m through for, at each iteration check that the element is positive, if so, write it to an intermediate array and go to the next one. iterations.
Then, outside of for, get the last element from the intermediate array and print a message to the console.

E
Egor, 2020-10-06
@exorka

Isn't it easier to sort the array and display Max?

D
Dmitry Pavlov, 2020-10-06
@Stalker31

int count=0;
double number,value;
value=-3;
number=value;
while(count<m.Lenght){//выполнять пока не дошли до конца массива
if(m[count]>0){
value=m[count];//его значение
number=count;//номер элемента
}
count++;
}
if(number==-3){
Console.Write("Нет положительных чисел"); 
}
else{
Console.Write("Последнее положительное число в массиве - " + value+ " имеет номер - "+number);
                    
}

S
Sergey, 2020-10-07
@Senarest

using System;

namespace LastPositiveNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int result = 0;
            int[] array = new int[10] { 1, 2, -5, 7, 9, -3, 4, 5, -7, -5 };

            foreach (var item in array)
                result = item > 0 ? item : result;

            if (result > 0)
                Console.WriteLine(result);
            else
                Console.WriteLine("Положительных чисел нет");
            Console.ReadLine();
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question