0

Here is my code :

using System;

namespace CappedSum
{
    class Program
    {
        static void Main(string[] args)
        {
            int sumLimit = Convert.ToInt32(Console.ReadLine());
            int sum = 0;
            int count = 0;
            while (sum<sumLimit)
            {
                int number = Convert.ToInt32(Console.ReadLine());
                if (sum + number < sumLimit)
                {
                    sum += number;
                    count++;
                }
                else if (sum + number > sumLimit)
                {
                    Console.WriteLine(sum + " " + count);
                }
            }
        }
    }
}

I had to write a console application that reads from the keyboard a list of numbers until their sum reaches a certain limit also entered by the user.

The limit is given on the first line, and on the next lines will be the list of numbers which has to be added. The program will stop reading when the sum of the numbers entered so far exceeds the limit and will display the last amount that did not exceed the limit, as well as how many numbers were needed to calculate it.

for example : if I enter 10 (which is the limit) then I enter 2,3,2,6. The result will be 7 (which is the last amount that did not exceed the limit) and 3 (which represents how many numbers needed to calculate it).

  • Change Console.ReadLine() to Console.ReadLine().Trim() – S. Walker Jan 04 '21 at 12:14
  • 1
    Does this answer your question? [int.Parse, Input string was not in a correct format](https://stackoverflow.com/questions/9372210/int-parse-input-string-was-not-in-a-correct-format) and [How the int.TryParse actually works](https://stackoverflow.com/questions/15294878/how-the-int-tryparse-actually-works) –  Jan 04 '21 at 12:15
  • I changed it, but the format exception still appears :( – Bodor Arianna Jan 04 '21 at 12:39

1 Answers1

0

Try out Int32.Parse instead of Convert.ToInt32. Also, a really basic I use sometimes to debug my same mistakes, is to write MessageBoxes after specific instructions, so if they do not work I never get to the message, viceversa if the message shows I know that works. I'd put two Messageboxes after the Int32.Parse(Console.Readline()) being like MessageBox.Show(sumlimit/number.ToString());. This way you know how far the code works.