Как найти отрицательные числа в наборе с

I have a array int[] numArray . I want to know is there any straight forward way to just check whether array has negative numbers in it ?

If there is no direct method even linq will do . I am bit new to linq . Can anyone suggest ?

asked Sep 30, 2011 at 13:56

Kuntady Nithesh's user avatar

Kuntady NitheshKuntady Nithesh

11.3k19 gold badges61 silver badges86 bronze badges

If you’re open to using LINQ:

var containsNegatives = numArray.Any(n => n < 0);

Or, if you want to do it the “old fashioned” way…you just have to loop:

var containsNegatives = false;

foreach(var n in numArray)
{
    if(n < 0)
    {
        containsNegatives = true;
        break;
    }
}

And if you really want to get fancy, you could turn that into an Extension method:

public static class EnumerableExtensions
{
    public static bool ContainsNegatives(this IEnumerable<int> numbers)
    {
        foreach(n in numbers)
        {
            if(n < 0) return true;
        }

        return false;
    }
}

And call it from your code like:

var containsNegatives = numArray.ContainsNegatives();

answered Sep 30, 2011 at 13:58

Justin Niessner's user avatar

Justin NiessnerJustin Niessner

241k40 gold badges406 silver badges536 bronze badges

2

You could use Any:

bool containsNegative = numArray.Any(i => i < 0)

Or

bool containsNegative = numArray.Min() < 0;

EDIT

int[] negativeNumbers = numArray.Where(i => i < 0).ToArray();

answered Sep 30, 2011 at 13:59

Joe's user avatar

2

var negativeExist = numArray.Any(a => a < 0);

answered Sep 30, 2011 at 13:58

John Hartsock's user avatar

John HartsockJohn Hartsock

84.9k23 gold badges131 silver badges146 bronze badges

0

You can use Array.Find(T) method to perform this task.

public static T Find<T>(
    T[] array,
    Predicate<T> match
)

For example,

using System;
using System.Drawing;

public class Example
{
    public static void Main()
    {
        // Create an array of five Point structures.
        Point[] points = { new Point(100, 200), 
            new Point(150, 250), new Point(250, 375), 
            new Point(275, 395), new Point(295, 450) };

        // To find the first Point structure for which X times Y 
        // is greater than 100000, pass the array and a delegate
        // that represents the ProductGT10 method to the static 
        // Find method of the Array class. 
        Point first = Array.Find(points, ProductGT10);

        // Note that you do not need to create the delegate 
        // explicitly, or to specify the type parameter of the 
        // generic method, because the C# compiler has enough
        // context to determine that information for you.

        // Display the first structure found.
        Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
    }

    // This method implements the test condition for the Find
    // method.
    private static bool ProductGT10(Point p)
    {
        if (p.X * p.Y > 100000)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* This code example produces the following output:

Found: X = 275, Y = 395
 */

answered Sep 30, 2011 at 13:58

Traditional:

foreach (int number in numArray) { if (number < 0) return true; }
return false;

With LINQ:

bool result = numArray.Any(x => x < 0);

answered Sep 30, 2011 at 13:59

Andreas's user avatar

AndreasAndreas

6,4452 gold badges34 silver badges46 bronze badges

A bit twidling version would be

public static bool AnyNegative(int[] arr){
  const long firstBit = 2147483648;
  var res = false;
  for (var i = 0; i < arr.Length && !res; i++) res = (arr[i] & firstBit) == firstBit;
  return res;
}

you can the call it like this>

int arr = {...}
  if(arr.AnyNegative()){
      //do stuf if there's any negative numbers
  }

of course this is just an obfuscated version of

public static bool AnyNegative(int[] arr){
            var res = false;
            for (var i = 0; i < arr.Length && !res; i++) res = arr[i] < 0;
            return res;
}

answered Sep 30, 2011 at 14:12

Rune FS's user avatar

Rune FSRune FS

21.4k7 gold badges61 silver badges96 bronze badges

3

AFI04

0 / 0 / 0

Регистрация: 27.11.2021

Сообщений: 15

1

Найти в списке отрицательные элементы и вывести их на экран

27.11.2021, 19:08. Показов 3030. Ответов 1

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

нужно вывести все отрицательные элементы в списке
Кое что я сделал, но не знаю что писать после if:

C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
int main() {
    list <int> v = { 12, -5, 12, -35 };
    list <int>::iterator i;
    for (i = v.begin(); i != v.end(); i++) {
        if 
    }
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

27.11.2021, 19:08

Ответы с готовыми решениями:

В файле найти отрицательные элементы, и когда они есть, то вывести их на экран
Написать программу, которая в файле, ищет отрицательные элементы, и когда они есть, то выводит их…

Найти максимальный элемент, сумму чётных элементов массива и вывести отрицательные элементы на экран
Дан одномерный массив, состоящий из N целочисленных элементов.
11.1. Ввести массив с клавиатуры….

Найти и вывести на экран все нечетные отрицательные элементы массива и вычислить сумму нечетных элементов
1. Дан массив А из К целых чисел. Найти и вывести на экран все нечетные отрицательные элементы…

Найти в односвязном списке отрицательные элементы и удалить их
Нужно в списке, типа очередь находить отрицательные элементы и удалять их.
Написал код, но почему…

1

nmcf

7508 / 6382 / 2905

Регистрация: 14.04.2014

Сообщений: 27,779

27.11.2021, 19:31

2

Лучший ответ Сообщение было отмечено AFI04 как решение

Решение

C++
1
if (*i < 0)



1



#include<stdio.h>
#include<math.h>

// Найти несколько чисел в наборе чисел и вывести их в положительном и обратном порядке, а также определить положительные и отрицательные числа

int NumCount(int n)
{
	 int count = 0; // Объявляем начальное значение 0
	while(n != 0)
	{
		count++;//1   2   3
		n /= 10;//123/10 ==12    12/10==1   1/10 == 0
	}
	 printf ("% d  n", count); // Количество отпечатков
	return count;
}


void PrintOrder(int n)
{
	if(n==0)
     {
      printf("0");
      return;
     }
    if(n<0)
    {
     printf("-");
     n=-n;
    }
    int figures=NumCount(n);
         int power = (int) pow ((float) 10, (float) (figure-1)); // pow (x, y), его роль состоит в том, чтобы вычислять y-степень x. x, y не может быть целым одновременно.
    int tmp=0;
    while(power!=0)
    {
       tmp=n/power;
       printf("%d ",tmp);
       n=n%power;
       power=power/10;
     }
	
	return ;
}


void PrintRever(int n)
{
	if(n == 0)
	{
		printf("0n");
		return;
	}

	if(n < 0)
	{
		printf("- ");
		n = -n;
	}
	int tmp = 0;
	while(n != 0)
	{
		tmp = n % 10;//123 % 10 == 3
		printf("%d ",tmp);
		n /= 10;//123 /10 = 12
	}
	printf("n");
}

int main()
{
	
	PrintOrder(123);
	PrintRever(-123);
	
	getchar();
	return 0;
}

Ответ: 3. 1 2 3, -3 2 1

Подождите!

Не закрывайте страницу. Нейросеть пишет ответ. Он появится тут.

Этот ответ написан нейросетью.

Искуственный интеллект во многом преуспевает, но в некоторых областях может давать неточные ответы.
Если вам не понравился ответ, попробуйте задать его более развёрнуто и конкретно, используя точные параметры.

Ответ нейросети:

Для решения данной задачи на C# нужно написать программу, которая принимает три целых числа от пользователя, а затем считает, сколько из них положительных и сколько отрицательных. Для этого можно использовать стандартные математические операции и условные операторы.

Ниже приведен пример кода на C# для решения этой задачи:

using System;



class Program {

   static void Main(string[] args) {

       int a, b, c, positiveCount = 0, negativeCount = 0;

       Console.Write("Введите первое число: ");

       a = int.Parse(Console.ReadLine());

       Console.Write("Введите второе число: ");

       b = int.Parse(Console.ReadLine());

       Console.Write("Введите третье число: ");

       c = int.Parse(Console.ReadLine());

       

       if (a > 0) 

           positiveCount++;

       else if (a < 0)

           negativeCount++;

           

       if (b > 0) 

           positiveCount++;

       else if (b < 0)

           negativeCount++;

           

       if (c > 0) 

           positiveCount++;

       else if (c < 0)

           negativeCount++;



       Console.WriteLine("Количество положительных чисел: " + positiveCount);

       Console.WriteLine("Количество отрицательных чисел: " + negativeCount);

   }

}

В этом примере пользователь вводит три целых числа, которые сохраняются в переменные `a`, `b` и `c`. После этого происходит проверка каждой переменной: если она больше 0, то к переменной `positiveCount` добавляется единица; если она меньше 0, то к переменной `negativeCount` добавляется единица.

В результате в консоль выводится количество положительных и отрицательных чисел. Если все три числа равны 0, то программа не выводит ничего.

⚠️Зарепортить пост!

Добавить комментарий