-
-
Notifications
You must be signed in to change notification settings - Fork 3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
make fold.expresion.cpp
work with negative values
#268
base: master
Are you sure you want to change the base?
Conversation
Do not use 'auto' for the return of template functions, but use 'double' instead |
@@ -11,8 +11,8 @@ | |||
#include <iostream> | |||
template<typename ... T> | |||
auto average(T ... t) { | |||
return (t + ... ) / sizeof...(t); | |||
return static_cast<double>((t + ... )) / sizeof...(t); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
我个人建议是模仿 <cmath>
中浮点函数的额外重载,把整数类型转换为 double
而浮点类型不变。这样可以避免 long double
被转换为 double
。
return static_cast<double>((t + ... )) / sizeof...(t); | |
constexpr auto integer_to_double = [](auto x) { | |
if constexpr (std::is_integral_v<decltype(x)>) | |
return static_cast<double>(x); | |
else | |
return x; | |
}; | |
return (integer_to_double(t) + ... ) / sizeof...(t); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
static_caste() it will explicitly change the data type of t to double
#include <iostream>
template<typename ... T>
auto average(T ... t) {
return (static_cast<double>(t) + ...) / sizeof...(t);
}
int main() {
std::cout << average(1, 2, 3, 4, 5, -6, -7, -8, -9, -10) << std::endl;
}
}
static_caste() it will explicitly change the data type of t to double #include <iostream>
template<typename ... T>
auto average(T ... t) {
return (static_cast<double>(t) + ...) / sizeof...(t);
}
int main() {
std::cout << average(1, 2, 3, 4, 5, -6, -7, -8, -9, -10) << std::endl;
} |
@@ -11,8 +11,8 @@ | |||
#include <iostream> | |||
template<typename ... T> | |||
auto average(T ... t) { | |||
return (t + ... ) / sizeof...(t); | |||
return static_cast<double>((t + ... )) / sizeof...(t); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
static_caste() it will explicitly change the data type of t to double
#include <iostream>
template<typename ... T>
auto average(T ... t) {
return (static_cast<double>(t) + ...) / sizeof...(t);
}
int main() {
std::cout << average(1, 2, 3, 4, 5, -6, -7, -8, -9, -10) << std::endl;
}
}
resolve #267
Description
Please describe the motivation of this pull request, and what problem was solved in this PR.
Change List
Reference
I added a
static_cast<double>
to make it work with negative values.说明
此处详细说明 PR 的动机是什么、解决了什么样的问题。
变化箱单
参考文献
如果有请注明