What if they say Operands / and * are not supported by the type of String data, though I moved them into int? (C#)



  • Code:

    using System;
    

    class Program {
    public static void Main(string[] args) {
    Console.WriteLine("Выберите действие (+ - * /)");
    string act;
    act = Console.ReadLine();
    Console.WriteLine("Введите первое число:");
    string a;
    a = Console.ReadLine();
    Convert.ToInt32(a);
    Console.WriteLine("Введите второе число:");
    string b;
    b = Console.ReadLine();
    Convert.ToInt32(b);
    if (act == "+") {
    Console.WriteLine($"Ответ: {a + b}");
    } else if (act == "-") {
    Console.WriteLine($"Ответ: {a - b}");
    } else if (act == "*") {
    Console.WriteLine($"Ответ: {a * b}");
    } else if (act == "/") {
    Console.WriteLine($"Ответ: {a / b}");
    } else {
    Console.WriteLine("Действие выбрано неверно");
    }
    }
    }

    Mistake:

    main.cs(21,48): error CS0019: Operator *' cannot be applied to operands of type string' and string' main.cs(23,48): error CS0019: Operator /' cannot be applied to operands of type string' and string'
    Compilation failed: 3 error(s), 0 warnings

    I moved variables a and b in Int, Convert.ToInt32(a), Convert.ToInt32(b) but it doesn't work, the program still thinks I'm working with the line.
    What do we do?



  • Well, I'll write my answer too.

    In C#, all variables and constants cannot change their type of data after they have been declared. For this reason (and possibly a couple of others) all changes and transformations are meant to create a new variable based on the meaning of old and to return this new variable.

    Method Convert.ToInt32(...); accepts as an argument the line, creates a number on its basis and returns it as a result. The line is not turning into number!

    You can keep the value reverted by the method to the variable to use it in the future:

    string aString = "1";
    int aNumber    = Convert.ToInt32(number1String); // строка осталось строкой; aNumber = 1
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2