ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1820. Ural Steaks

C++ strange behavior
Posted by Ostrovski 12 Sep 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
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
Posted by Ostrovski 13 Sep 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
Posted by TedEBear 20 Feb 2012 22:03
Another way is
(int)ceil((a*2)/b);
given that a and b are doubles and cmath is included.