ENG  RUSTimus Online Judge
Online Judge
Задачи
Авторы
Соревнования
О системе
Часто задаваемые вопросы
Новости сайта
Форум
Ссылки
Архив задач
Отправить на проверку
Состояние проверки
Руководство
Регистрация
Исправить данные
Рейтинг авторов
Текущее соревнование
Расписание
Прошедшие соревнования
Правила
вернуться в форум

Обсуждение задачи 1820. Уральские бифштексы

C++ strange behavior
Послано Ostrovski 12 сен 2011 12:22
Why this code is working incorrectly:
#include <iostream>

using namespace std;

int main()
{
    int n, k;
    cin >> n >> k;

    if (k >= n)
        cout << 2;
    else
        cout << 2*n/k + (2*n%k)? 1 : 0;
}
In test #13 (n == 7 && k ==3) this code give 6, but it`s wrong! Properly answer is 5... However on other tests with number less then 13 code is working good.
Separate output of values (2*n/k) and ((2*n%k)? 1 : 0) in test #13 gives results 4 and 2 correspondly. It`s very strange for me. Who can explain this behavior? Right here or in ICQ 303358. I will be very thankful =)

P.S.
This code changing solves the problem:
...
int main()
{
    int n, k;  cin >> n >> k;
    if (k >= n){ cout << 2; return 0; }

    int add = 0;
    if (2*n%k) add++;

    cout << 2*n/k + add;
}

But methinks, that first code should working too.

P.P.S. Sorry for my English...
Re: C++ strange behavior
Послано ...†.†.†... Stigius ...†.†.†... 13 сен 2011 15:12
Just be careful with operator priorities. Your first code works as
(cout << 2*n/k + (2*n%k)) ? 1 : 0;
Wrap ternary operator with brackets, that is
cout << 2*n/k + ((2*n%k) ? 1 : 0);
and everything will be ok.
Re: C++ strange behavior
Послано Ostrovski 13 сен 2011 15:43
Thank you, comrade! I`m forgotten that ternary operator has one of the lowest operations priority. Now it`s all right!
Re: C++ strange behavior
Послано TedEBear 20 фев 2012 22:03
Another way is
(int)ceil((a*2)/b);
given that a and b are doubles and cmath is included.