c++ - 简单的计数和求和函数没有按我预期的方式工作

标签 c++

我刚开始使用 C++ 中的函数,所以请多多包涵。我可以使用您提供的任何提示。

我正在尝试编写一个程序,让我知道从 1 到 10 有多少个数字可以被 3 整除,并且它应该将这些数字相加。

所以我的代码应该输出:

There are 3 numbers divisible by 3, sum of those numbers: 18

但它正在输出:

There are 1 numbers divisible by 3, sum of those numbers: 9

我被困了几个小时,我不明白缺少了什么或出了什么问题。

#include <stdio.h>
#include <stdlib.h>

int Amount_of_Numbers_Divisible_By_3(int x);
int Sum_of_Numbers_Divisible_By_3(int y);

int main() {
    int amount_variable, sum_variable;

    for (int i = 1; i < 10; i++) {
        amount_variable = Amount_of_Numbers_Divisible_By_3(i);
        sum_variable = Sum_of_Numbers_Divisible_By_3(i);
    }
    printf("There are %d numbers divisible by 3, sum of those numbers: %d\n",amount_variable, sum_variable);

    return 0;
}

int Amount_of_Numbers_Divisible_By_3(int x) 
{
    int amount_of_numbers;

    if (x % 3 == 0) {
        amount_of_numbers++;
    } 

    return amount_of_numbers;
}

int Sum_of_Numbers_Divisible_By_3(int y)
{
    int sum_of_numbers = 0;

    if (y % 3 == 0) {
        sum_of_numbers += y;
    }

    return sum_of_numbers;
}

最佳答案

问题是您的 amount_of_numberssum_of_numbers 都是堆栈变量(已初始化)。即使您对它们进行了零初始化,它们也不会返回真正的总数,它们只会为 amount_of_numbers 返回 1 或 0 以及为 sum_of_numbers 传入的数字。为了使您的函数按原样运行,您需要传入总数并修改或返回新值。

但是让我们谈谈更好的方法:

  • 你知道 1 和给定数字之间有多少个 3 的倍数,用它除以 3
  • 通过找到 triangular number 可以知道这些数字的总和该计数乘以 3

所以给定一个数字 const int n 你可以找到:

  • const auto amount_of_numbers = n/3
  • const auto sum_of_numbers = 3 * (amount_of_numbers * (amount_of_numbers + 1)/2)

如果您需要在函数中使用它,您可以这样做:

pair<int, int> Numbers_Divisible_By_3(const int x) {
    const auto amount_of_numbers = x / 3;
    const auto sum_of_numbers = 3 * (amount_of_numbers * (amount_of_numbers + 1) / 2);

    return { amount_of_numbers, sum_of_numbers };
}

如果您想查找 1 到 10 之间的数字的结果,您可以简单地调用:Numbers_Divisible_By_3(10)

Live Example

关于c++ - 简单的计数和求和函数没有按我预期的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946440/

相关文章:

C++调用静态函数指针

c++ - Random123使用visual studio为opencl生成随机数

c++ - 为什么这段代码不能编译?

c++ - 体系结构 x86_64 : "alglib::spline2dcalc(alglib::spline2dinterpolant const&, double, double, alglib::xparams)" 的 undefined symbol

c++ - 内存使用的理论和问题

c++ - 如何使用 QxtGlobalShortcut 库检测 Qt 中的按键释放事件

c++ - 禁用照明的 OpenGL 绘图丢失其 "depth"

c++ - 使用数组 vector 的正确方法

c++ - 如何测量并行 C++ 程序中的网络延迟?

c++ - 寻求理解 typedef