Выражение не дает результат со знаком '-'
От: overt Ниоткуда  
Дата: 09.07.08 11:10
Оценка:
Следующее выражение никогда не дает отрицательного результата, хотя функция sign() точно возвращает как -1, так и +1. Почему?

unsigned X;
// ....
double shX = sign() * rand() % (X / 10) + 1;
(MS VS 7.1/8.0)
Re: Выражение не дает результат со знаком '-'
От: overt Ниоткуда  
Дата: 09.07.08 11:16
Оценка:
Здравствуйте, overt, Вы писали:

O>Следующее выражение никогда не дает отрицательного результата, хотя функция sign() точно возвращает как -1, так и +1. Почему?


O>
O>unsigned X;
O>// ....
O>double shX = sign() * rand() % (X / 10) + 1;
O>


Переставил приоритеты и сделал приведение:
double shX = sign() * (int)(rand() % (X / 10) + 1);


жалоба пропала, но почему выражение (rand() % (X / 10) + 1) приводилось к unsigned понять не могу.
(MS VS 7.1/8.0)
Re: Выражение не дает результат со знаком '-'
От: Fwiffo Россия  
Дата: 09.07.08 11:29
Оценка: 1 (1)
Здравствуйте, overt, Вы писали:

O>Следующее выражение никогда не дает отрицательного результата, хотя функция sign() точно возвращает как -1, так и +1. Почему?


O>
O>unsigned X;
O>// ....
O>double shX = sign() * rand() % (X / 10) + 1;
O>


В результате умножения int на unsigned int получается unsigned int:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This partem is called the usual arithmetic conversions, which are defined as follows:
— If either operand is of type long double, the other shall be converted to long double.
— Otherwise, if either operand is double, the other shall be converted to double.
— Otherwise, if either operand is float, the other shall be converted to float.
— 0|therwise. the integral promotions (4|.5) shall be performed on both operands.54'1
— Then, if either operand is unsigned long the other shall be convened to unsigned long.
— Otherwise, if one operand is a long int and the other unsigned int. then if a long int can represent all the values of an unsigned int. the unsigned int shall be converted to a long int: otherwise both operands shall be convened to unsigned long int.
— Otherwise, if either operand is long, the other shall be converted to long.
— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.