Error cs0019 operator cannot be applied to operands of type double and double

I have tried working on a vector addition code in C#, and part of it involves using math to determine X and Y values for a vector, and for some reason it gives me the error saying I cannot multiply...

I have tried working on a vector addition code in C#, and part of it involves using math to determine X and Y values for a vector, and for some reason it gives me the error saying I cannot multiply an array value with a double precision floating point value. I have tried converting, but that has only created more errors. Here is my code:

using System;
using System.Windows.Forms;

    namespace VectorAddEdit
    {
        public partial class Form1 : Form
        {
            double[] mag = new double[5];
            double[] ang = new double[5];
            int cnt = 0;
            public Form1()
            {
                InitializeComponent();
            }

            private void textBox1_TextChanged(object sender, EventArgs e)
            {

            }

            private void textBox2_TextChanged(object sender, EventArgs e)
            {

            }

            private void textBox4_TextChanged(object sender, EventArgs e)
            {

            }

            private void textBox5_TextChanged(object sender, EventArgs e)
            {

            }

            private void button1_Click(object sender, EventArgs e)
            {
                while (cnt < 5)
                {
                    if (textBox1.Text == "" || textBox2.Text == "")
                    {
                        MessageBox.Show("You did not enter data into the correct boxes!");
                        System.Threading.Thread.Sleep(1000);
                        Application.Exit();
                    }

                    mag[cnt] = Convert.ToDouble(textBox1.Text);
                    ang[cnt] = Convert.ToDouble(textBox2.Text);

                    Console.ReadLine();

                    cnt++;
                }
            }

            private void button2_Click(object sender, EventArgs e)
            {
                double xsummag = 0;
                double ysummag = 0;
                double resultmag;
                double resultang;


                for (int i = 0; i < cnt; i++)
                {
                    xsummag = mag * Math.Cos(ang * Math.PI / 180) + xsummag;
                    ysummag = mag * Math.Sin(ang * Math.PI / 180) + ysummag;
                }

                resultmag = Math.Sqrt(Math.Pow(xsummag, 2) + Math.Pow(ysummag, 2));
                resultang = Math.Atan(ysummag / xsummag) * 180 / Math.PI;

                if (xsummag < 0 && ysummag > 0)
                    resultang = resultang + 180;

                else if (xsummag < 0 && ysummag < 0)
                    resultang = resultang + 180;

                else if (xsummag > 0 && ysummag < 0)
                    resultang = resultang + 360;

                textBox4.Text = resultmag.ToString();

                textBox5.Text = resultang.ToString();
            }

            private void button3_Click(object sender, EventArgs e)
            {
                System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"C:WindowsMediaAlarm09.wav");

                player.Play();
                Application.DoEvents();
                System.Threading.Thread.Sleep(1000);

                Application.Exit();
            }
        }
    }

The error occurs on 2 lines where xsummag and ysummag are assigned.
If anyone can help me resolve this error, I would greatly appreciate it. :)

Slavormund

0 / 0 / 0

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

Сообщений: 31

1

25.01.2021, 19:55. Показов 5052. Ответов 4

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


Я не понимаю в чем проблема,вроде подобное уже делал,но не могу понять

Ошибка:
Оператор «&&» невозможно применить к операнду типа «int» и «int».
c 56 строки можно смотреть

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Math;
 
namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            int k, l, m, n;
            Console.WriteLine("Положение коня: ");
            while (true)
            {
                Console.Write("k= ");
                k = int.Parse(Console.ReadLine());
                if (k < 1 || k > 8)
                {
                    Console.WriteLine("нужно ввести число от 1 до 8!");
                    continue;
                }
                Console.Write("l= ");
                l = int.Parse(Console.ReadLine());
                if (l < 1 || l > 8)
                {
                    Console.WriteLine("нужно ввести число от 1 до 8!");
                    continue;
                }
                break;
            }
            Console.WriteLine("Поле для хода: ");
            while (true)
            {
                Console.Write("k= ");
                m = int.Parse(Console.ReadLine());
                if (m < 1 || m > 8)
                {
                    Console.WriteLine("нужно ввести число от 1 до 8!");
                    continue;
                }
                Console.Write("l= ");
                n = int.Parse(Console.ReadLine());
                if (n < 1 || n > 8)
                {
                    Console.WriteLine("нужно ввести число от 1 до 8!");
                    continue;
                }
                break;
            }
            int a, b;
            a = Abs(k - n);
            b = Abs(l - n);
            if (((a = 1) && (b = 2)) || ((a = 2) && (b = 1)))
                Console.Write("Конь может за один ход попасть на заданное поле");
            else
                Console.Write("Конь не может за один ход попасть на заданное поле"); 
            Console.ReadKey();
        }
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



randok

612 / 392 / 187

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

Сообщений: 852

25.01.2021, 19:58

2

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

Решение

C#
1
if (((a = 1) && (b = 2)) || ((a = 2) && (b = 1)))

замените на

C#
1
if (a == 1 && b == 2 || a == 2 && b == 1)

И вот тут будет ошибка

C#
1
2
a = Abs(k - n);
b = Abs(l - n);

Если конечно Abs это не какой-то ваш метод.

C#
1
2
a = Math.Abs(k - n);
b = Math.Abs(l - n);



1



1483 / 880 / 321

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

Сообщений: 3,351

25.01.2021, 20:01

3

Цитата
Сообщение от Slavormund
Посмотреть сообщение

if (((a = 1) && (b = 2))

= — оператор присваивания
== — оператор сравнения



1



0 / 0 / 0

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

Сообщений: 31

25.01.2021, 20:06

 [ТС]

4

с Abs нет ошибки, я использовал using static System.Math; чтобы не вызывать каждый раз класс Math (вроде правильно объяснил)



0



612 / 392 / 187

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

Сообщений: 852

25.01.2021, 20:13

5

Цитата
Сообщение от Slavormund
Посмотреть сообщение

чтобы не вызывать каждый раз класс Math

Я понял мысль, но лучше так не делать, вносит сумятицу при чтении кода. Вот я не посмотрел на юзинги и сразу в глаза бросился этот Abs. В общем, уводит внимание от привычного написания метода.



0



Оператор * РЕШЕНО

Оператор * РЕШЕНО

Пишу вот так:

Используется csharp

GameObject theSplat=(GameObject)Instantiate(splat,hit.point+(hit.normal * 2.5),Quaternion.identity);

Говорит:
Assets/Scripts/player_shoot.cs(38,106): error CS0019: Operator `*’ cannot be applied to operands of type `UnityEngine.Vector3′ and `double’

Что не так? :-?

Последний раз редактировалось bumer7721 12 авг 2012, 15:42, всего редактировалось 1 раз.

Аватара пользователя
bumer7721
UNIт
 
Сообщения: 102
Зарегистрирован: 29 июл 2011, 14:18

Re: Оператор *

Сообщение Syberex 12 авг 2012, 14:05

Говорит, что не может применить оператор * (умножение) к операндам типа Vector3 (hit.normal) и double (2.5).

А так если?

Используется csharp

GameObject theSplat=(GameObject)Instantiate(splat,hit.point+(hit.normal * 2.5f),Quaternion.identity);
 

Аватара пользователя
Syberex
Адепт
 
Сообщения: 2292
Зарегистрирован: 14 янв 2011, 20:35
Откуда: Кострома
  • Сайт

Re: Оператор *

Сообщение Paul Siberdt 12 авг 2012, 14:39

Зато все на сишарпах ваяют, млять! Цирк! :ymparty: X(

Аватара пользователя
Paul Siberdt
Адепт
 
Сообщения: 5317
Зарегистрирован: 20 июн 2009, 21:24
Откуда: Moscow, Russia
Skype: siberdt
  • Сайт

Re: Оператор *

Сообщение bumer7721 12 авг 2012, 15:41

СПАСИБО!!! Помогло, я просто провтыкал, последнее время lua писал

Аватара пользователя
bumer7721
UNIт
 
Сообщения: 102
Зарегистрирован: 29 июл 2011, 14:18

Re: Оператор * РЕШЕНО

Сообщение Левш@ 12 авг 2012, 15:55

типа Vector3 (hit.normal) и double (2.5)

hit.normal != Vector3
hit.normal = Quaternion

Vector3 = hit.point

Аватара пользователя
Левш@
Адепт
 
Сообщения: 4073
Зарегистрирован: 14 окт 2009, 16:34
Откуда: IBERIA
Skype: bars_levsha
  • Сайт

Re: Оператор * РЕШЕНО

Сообщение Syberex 12 авг 2012, 16:16

Левш@ писал(а):

типа Vector3 (hit.normal) и double (2.5)

hit.normal != Vector3
hit.normal = Quaternion

Vector3 = hit.point

Как так квантернион? :D Можно ссылку?
И в сообщении об ошибке про квантернион ни слова, даже если предположить, что это так — как тогда растолковать сообщение об ошибке? Там что double * квантернион, получаем double и умножаем на Vector3 ???

Аватара пользователя
Syberex
Адепт
 
Сообщения: 2292
Зарегистрирован: 14 янв 2011, 20:35
Откуда: Кострома
  • Сайт

Re: Оператор * РЕШЕНО

Сообщение Левш@ 12 авг 2012, 16:22

Как так квантернион?

Сорьки, погорячился… :) hit.normal = вектор направление.
Имелось ввиду что это не point.position :ymsmug:

Аватара пользователя
Левш@
Адепт
 
Сообщения: 4073
Зарегистрирован: 14 окт 2009, 16:34
Откуда: IBERIA
Skype: bars_levsha
  • Сайт


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Yandex [Bot] и гости: 22



  • Remove From My Forums
  • Question

  • User-412682272 posted

    Hi,

    I have a DropDownList named ddlCluster, and I want to do a simle test:

    if (ddlCluster.SelectedValue == 0)

    {

         //some stuff goes here

    }

    Now this is returning this error: CS0019: Operator ‘==’ cannot be applied to operands of type ‘string’ and ‘int’

    ??????

    With VB.NET this seems to work. Any thoughts?

Answers

  • User-412682272 posted

    hi,

    I solved it by turning 0 into a string:

    if (ddlCluster.SelectedValue == «0»)

    Thanks for your time

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

private static object[] GetEnumLookupData<TEnum>() where TEnum: Enum
{
    var data = Enum.GetValues(typeof(TEnum))
        .OfType<TEnum>()
        .Where(e => e != default(TEnum))
        .Select(e => new {Id = e, Name = e.ToString()})
        .ToArray();

    return data;
}

This does not compile, but returns a error:

CS0019: Operator ‘!=’ cannot be applied to operands of type ‘TEnum’ and ‘TEnum’

What am I missing here? Isn’t it clear that TEnum is a value type?

The funniest thing is that if I omit (TEnum) in default(TEnum), so it is now e != default it compiles, but default generates porbably just a null because I see 0 value in created EF Core migration. WTF?!

I tried to use EqualityComparer<TEnum>.Default.Equals(...) and it kinda worked, however, EF Core 2.1 has a bug: migrations with seeding of data with emun as primary key are unstable. This bug is fixed only in EF Core 2.2 preview.
So I changed to int and …

private static object[] GetEnumLookupData<TEnum>() where TEnum: struct, Enum
{
    var comparer = EqualityComparer<TEnum>.Default;

    var data = Enum.GetValues(typeof(TEnum))
        .OfType<TEnum>()
        .Where(e => !comparer.Equals(e, default))
        .Select(e => new {Id = (int)e, Name = e.ToString()})
        .ToArray();

    return data;
}

CS0030 Cannot convert type ‘TEnum’ to ‘int’

C# Compiler Error Message

Operator ‘{0}’ cannot be applied to operands of type ‘{1}’ and ‘{2}’

Reason for the Error

You would usually get this error when you are using an operator that doesn’t support a specific data type. Below are some of the cases when you will receive this error.

  • When you use bool and think, it works as integer.
public class Hello {
    public static void Main() {
            bool input = true;
            if (input > 0) // This Line results in cs0019 error.
            {
                // Do something.
            }
    }
}

Error CS0019 Operator ‘>’ cannot be applied to operands of type ‘bool’ and ‘int’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 6 Active

  • When you compare an int with boolean
namespace ClassLibrary
{
    public class DeveloperPublish
    {
        public static void Main()
        {
            int input = 1;
            if (input == true)
            {
            }
        }
    }
}

You will receive the below error.

Error CS0019 Operator ‘==’ cannot be applied to operands of type ‘int’ and ‘bool’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 8 Active

Some of the Other common scenarios that would result with this error includes

  • When you use || operator on strings
  • When you use +,- on boolean.
  • When you use == with structs

Solution

To fix the error, ensure that you revisit the logic and ensure that the right operator is used for the operands in your .NET application.

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

I’m confused on what I’m doing wrong here.


Program.cs

using System;

class Program
{

    static string CheckSpeed(double speed)
    {
        if (CheckSpeed > 65)
        {
            Console.WriteLine("too fast");
        }
        else if (CheckSpeed < 45)
        {
            Console.WriteLine("too slow");
        }
        else
        {
            Console.WriteLine("speed ok");
        }
    }

    static void Main(string[] args)
    {
        // This should print "too slow".
        Console.WriteLine(CheckSpeed(44));
        // This should print "too fast".
        Console.WriteLine(CheckSpeed(88));
        // This should print "speed OK".
        Console.WriteLine(CheckSpeed(55));
    }

}

1 Answer

Atle Bjelland

Inside your method you are calling your method again instead of checking against the parameter.

Your code check for your if statements needs to be checking against speed not CheckSpeed.

    if (speed > 65)
    {
        Console.WriteLine("too fast");
    }
    else if (speed < 45)
    {
        Console.WriteLine("too slow");
    }
    else
    {
        Console.WriteLine("speed ok");
    }

Понравилась статья? Поделить с друзьями:
  • Error cs0019 operator cannot be applied to operands of type char and string
  • Error cs0019 operator cannot be applied to operands of type bool and int
  • Error cs0019 operator cannot be applied to operands of type bool and double
  • Error cs0006 не удалось найти файл метаданных microsoft vsa dll
  • Error cs0006 metadata file could not be found