Вы можете создать требуемый массив, сопоставив регулярное выражение каждому элементу исходного массива:
const array = [
"Asia <span class='hide'>1234</span>",
"Ireland <span class='hide'>65dhh</span>",
"US West<span class='hide'>323-hth</span>",
"Asia Pacific <span class='hide'>ap-ss-1</span>",
"US West <span class='hide'>us-323223-1</span>"
];
const newArray = array.map(item => item.replace(/.*<span.*>(.*?)<\/span>/, '$1'));
console.log(newArray);
int a = 59.0f / 4.0f + 0.5f;
Это работает только при присваивании int, так как отбрасывается все, что находится после '.'
Edit: Это решение будет работать только в самых простых случаях. Более надежным решением будет:
unsigned int round_closest(unsigned int dividend, unsigned int divisor)
{
return (dividend + (divisor / 2)) / divisor;
}
Стандартная идиома для округления целых чисел такова:
int a = (59 + (4 - 1)) / 4;
Вы прибавляете делитель минус единицу к делимому.
// To do (numer/denom), rounded to the nearest whole integer, use:
#define ROUND_DIVIDE(numer, denom) (((numer) + (denom) / 2) / (denom))
пример Использования:
int num = ROUND_DIVIDE(13,7); // 13/7 = 1.857 --> rounds to 2, so num is 2
Некоторые из этих ответов являются сумасшедшим взглядом! Codeface закрепил его хотя! (См. @0xC0DEFACE ответ здесь ). Мне действительно нравятся макрос без типов или gcc форма выражения оператора по функциональной форме, однако, таким образом, я записал этот ответ с подробным объяснением того, что я делаю (т.е.: почему это математически работает), и поместите его в 2 формы:
/// @brief ROUND_DIVIDE(numerator/denominator): round to the nearest whole integer when doing
/// *integer* division only
/// @details This works on *integers only* since it assumes integer truncation will take place automatically
/// during the division!
/// @notes The concept is this: add 1/2 to any number to get it to round to the nearest whole integer
/// after integer trunction.
/// Examples: 2.74 + 0.5 = 3.24 --> 3 when truncated
/// 2.99 + 0.5 = 3.49 --> 3 when truncated
/// 2.50 + 0.5 = 3.00 --> 3 when truncated
/// 2.49 + 0.5 = 2.99 --> 2 when truncated
/// 2.00 + 0.5 = 2.50 --> 2 when truncated
/// 1.75 + 0.5 = 2.25 --> 2 when truncated
/// To add 1/2 in integer terms, you must do it *before* the division. This is achieved by
/// adding 1/2*denominator, which is (denominator/2), to the numerator before the division.
/// ie: `rounded_division = (numer + denom/2)/denom`.
/// ==Proof==: 1/2 is the same as (denom/2)/denom. Therefore, (numer/denom) + 1/2 becomes
/// (numer/denom) + (denom/2)/denom. They have a common denominator, so combine terms and you get:
/// (numer + denom/2)/denom, which is the answer above.
/// @param[in] numerator any integer type numerator; ex: uint8_t, uint16_t, uint32_t, int8_t, int16_t, int32_t, etc
/// @param[in] denominator any integer type denominator; ex: uint8_t, uint16_t, uint32_t, int8_t, int16_t, int32_t, etc
/// @return The result of the (numerator/denominator) division rounded to the nearest *whole integer*!
#define ROUND_DIVIDE(numerator, denominator) (((numerator) + (denominator) / 2) / (denominator))
См. немного больше по gcc выражениям оператора здесь .
/// @brief *gcc statement expression* form of the above macro
#define ROUND_DIVIDE2(numerator, denominator) \
({ \
__typeof__ (numerator) numerator_ = (numerator); \
__typeof__ (denominator) denominator_ = (denominator); \
numerator_ + (denominator_ / 2) / denominator_; \
})
BASE 2 CONCEPT:
для получения дополнительной информации! Как написано, вы выполняете целочисленную арифметику, которая автоматически просто обрезает любые десятичные результаты. Чтобы выполнить арифметику с плавающей запятой, либо измените константы на значения с плавающей запятой:
int a = round(59.0 / 4);
, либо приведите их к float
или другому типу с плавающей запятой:
int a = round((float)59 / 4);
В любом случае вам нужно выполнить окончательное округление с функцией round ()
в заголовке math.h
, поэтому обязательно #include
и используйте компилятор, совместимый с C99.