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

Simple count and sum functions are not working the way I expect

本文关键字:方式 工作 求和 简单 函数      更新时间:2023-10-16

我刚刚开始使用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: %dn",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都是堆栈变量(它们是单位化的(。即使您确实对它们进行了零初始化,而不是返回真正的总数,它们也只会返回 1 或 0 表示amount_of_numbers和传入的数字sum_of_numbers。为了使函数按原样工作,您需要传入总计并修改或返回新值。

但是,让我们谈谈更好的方法来做到这一点:

  • 你知道 1 和给定数字之间有多少个 3 的倍数
  • ,只需将其除以 3
  • 您可以通过找到该计数的三角形数字乘以 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)

现场示例

函数内声明的所有变量都只有函数内部相关的作用域。在外面,即使变量名在其他地方相同,它也没有意义。
因此,必须将amount_of_numbers和sum_of_numbers作为对函数的引用传递:

#include <stdio.h>
#include <stdlib.h>
void Amount_of_Numbers_Divisible_By_3(int x, int& amount_of_numbers);
void Sum_of_Numbers_Divisible_By_3(int y, int& sum_of_numbers);
int main() {
int amount_variable=0, sum_variable=0;
for (int i = 1; i < 10; i++) {
Amount_of_Numbers_Divisible_By_3(i, amount_variable);
Sum_of_Numbers_Divisible_By_3(i, sum_variable);
}
printf("There are %d numbers divisible by 3, sum of those numbers: %dn", amount_variable, sum_variable);
return 0;
}
void Amount_of_Numbers_Divisible_By_3(int x, int & amount_of_numbers)
{
if (x % 3 == 0) {
amount_of_numbers++;
}
}
void Sum_of_Numbers_Divisible_By_3(int y, int & sum_of_numbers)
{
if (y % 3 == 0) {
sum_of_numbers += y;
}
}

在我看来,你必须把这个x % 3 == 0改成x / 3 == 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;
}

在这种情况下,可整除数 3(有:3,6,9(; 总和:3+6+9=18

相关文章: