Home > Software design >  How can do calculations inside a string?
How can do calculations inside a string?

Time:10-21

How do i use operands in this code? What can i do to resolve this problem? Any suggestions or links to tutorials would be appreciated.

Operator '%' cannot be applied to operands of type 'string' 'int'

       int i = 0;
       double[] arr1 = new double[20];                                                        
       for (i = 0; i < 20; i  )
        {

            Console.Write("Enter a number (0=stop): ");
            var year = Console.ReadLine(); 
            if (year == "0") break;
            arr1[i] = int.Parse(year);



            while (year != 0)
            {


                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
                {
                    Console.WriteLine($"{year} is a leap year.");

                }
                else if (year < 0)
                {
                    Console.WriteLine($"Year must be positive!");

                }
                else
                {
                    Console.WriteLine($"{year} is not a leap year.");
                }`

CodePudding user response:

You are close. You are already parsing the string to an int. Just use that instead of the string year when doing your calculations. Also, I'm not sure what you're trying to do with that while loop but I don't think you need it. It seems to just cause your program to go in an infinite loop because while is evaluating year but there is no opportunity to change the year value within the while loop.

    void Main()
{
    int i = 0;
    double[] arr1 = new double[20];

    for (i = 0; i < 20; i  )
    {
        Console.Write("Enter a number (0=stop): ");
        var line = Console.ReadLine();
        
        int numYear = int.Parse(line);
        arr1[i] = numYear;
        string message = "" ;

        if (line != "0") 
        {
            if (numYear < 0)
            {
                message = "Year must be positive!";
            }
            else if ((numYear % 4 == 0) && (numYear % 100 != 0)) || (numYear % 400 == 0))
            {
                message = $"{numYear} is a leap year.");
            }
            else
            {
                message = $"{numYear} is not a leap year.");
            }
            Console.WriteLine(message);
        }
    }
}
  •  Tags:  
  • c#
  • Related