Skip to content
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

Chapter 2 exercise answer bug #267

Open
ZenoTan opened this issue Jul 16, 2023 · 2 comments · May be fixed by #268
Open

Chapter 2 exercise answer bug #267

ZenoTan opened this issue Jul 16, 2023 · 2 comments · May be fixed by #268

Comments

@ZenoTan
Copy link

ZenoTan commented Jul 16, 2023

The exercise answer could not handle negative values:

template<typename ... T>
auto average(T ... t) {
    return (t + ... ) / sizeof...(t);
}
int main() {
    std::cout << average(1, 2, 3, 4, 5, -6, -7, -8, -9, -10) << std::endl;
}

It would return 1844674407370955159 on my side since it deduced the return value to be unsigned int.

@Delta456 Delta456 linked a pull request Jul 16, 2023 that will close this issue
@Prathamesh01110
Copy link

The issue you're facing is due to integer promotion in C++. When you perform operations on values of different types, C++ promotes them to a common type before performing the operation. In your case, the values you're passing to the average function include both positive and negative integers, which leads to integer promotion.

The problem is that the sizeof...(t) part of your code is evaluated as an unsigned integer (size_t), which causes all the values to be promoted to unsigned integers for the division operation. This is why you're getting an unexpected result.

To fix this issue, you can explicitly cast the result of the division to the desired type (e.g., double) to ensure that the division is performed with the correct type. Here's an updated version of your code:

#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;
}

By casting the result of (t + ...), you ensure that the division is performed using a floating-point type, which can handle both positive and negative values correctly. This will give you the expected average, including negative values.

@Delta456
Copy link
Contributor

Delta456 commented Oct 1, 2023

I have made a PR for fixing this bug. See #268

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants