|
|
вернуться в форумC++ strange behavior 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 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 Another way is (int)ceil((a*2)/b); given that a and b are doubles and cmath is included. |
|
|