K
K
komy_ccilky_kidaesh_pidr2018-10-28 13:47:51
C++ / C#
komy_ccilky_kidaesh_pidr, 2018-10-28 13:47:51

Can't find an error in a loop?

Find the sum of integer negative odd numbers greater than -100
Why does it give different answers, they must be the same.
In the loop with parameter -2500, and in the other two -2499

Source
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Math;

namespace pr3._2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Задание №2";
            Console.SetCursorPosition(28, 4);
            Console.WriteLine("Условие задания №2");
            Console.SetCursorPosition(20, 5);
            Console.WriteLine("Найти сумму целых отрицательных нечетных чисел, больших  -100");
            int s=0;
            for (int i=-1; i>-100 && i<0; i--)
            {
                if (!(i%2==0))
                s = s+i;
            }

            int summ = 0;
            int k = -1;
            while (k>-100)
            {
                k--;
                if (!(k % 2 == 0) && k<0)
                    summ = summ + k;
            }

            int su = 0;
            int ls = -1;
            do
            {
                ls--;
                if (!(ls % 2 == 0) && ls<0)
                    su = su + ls;
            }
            while (ls > -100);
            Console.SetCursorPosition(20, 8);
            Console.Write("Сумма равна = {0}" , s);
            Console.SetCursorPosition(20, 9);
            Console.Write("Сумма равна = {0}", summ);
            Console.SetCursorPosition(20, 10);
            Console.Write("Сумма равна = {0}", su);
            Console.ReadKey();

        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bask, 2018-10-28
@komy_ccilky_kidaesh_pidr

k-- and ls-- must be put AFTER the condition is checked, not before

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question