如何查找数字大于 5 的数字总和

How to find the sum of numbers that have digits higher than 5

本文关键字:数字 大于 何查找 查找      更新时间:2023-10-16

所以我想写一个函数,返回数组中数字大于 5 的所有数字的总和,例如,如果数组是 [12, 66, 23, 67],答案将是 66+67 这段代码对数组中的所有数字求和,我无法弄清楚为什么


using namespace std;
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){
n[i]= n[i]/10;

}
else break;
}
S=S+a;
}
return S;   
}
int main()
{
int n[3], i;
for(int i=0; i<3; i++){
cin>>n[i];

}
cout<<func(n, 3)<<endl;
return 0;
}```

S=S+a这段代码不在while 循环中,而是在 for 循环中,这将添加数组中的所有元素

主要问题是您没有检查何时应该将a添加到S
这些行导致了问题:

int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){    // Wrong. Do "digit > 5"
n[i]= n[i]/10;
}
else break;      <--- exiting this while loop
}
S=S+a;               <--- ...but still adding?
}
return S;   
}

你正在打破循环,但仍然增加了总和。
您应该使用标志。您的内部循环如下所示:

// We need to check if each digit is valid
bool each_digit_greater_than_5 = true;
// As long as we have digits left and all previous digits were valid
while(n[i] != 0 && each_digit_greater_than_5)
{
// Extract a digit
digit = n[i] % 10;
// If valid, get next digit to extract
if(digit > 5)
{
n[i] /= 10;
}
// Else, exit the loop
else
{
each_digit_greater_than_5 = false;
}
}

然后,只需检查each_digit_greater_than_5

// If number was valid
if(each_digit_greater_than_5)
{
// Add to sum
S = S + a;
}

额外说明:

如何编写代码通常比编写的内容更重要。
这里有(一些(思考的食物。

  • 使用更好的格式:整个代码块应统一缩进。这:
...
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
...

既令人困惑又不清楚。对每个单独的块使用相同的缩进:

...
for(int i=0; i<size; i++){         // The base block
a= n[i];                       // new block start, add indent
while( n[i]!=0){               // same block, same indent
digit= n[i]%10;            // new block, add indent
...
使用
  • 更好的命名:不要使用San,除非它们非常清楚。
    digit是一个不错的选择,所以要归功于这一点!
    在这里,最好使用:
sum_of_special_numbers

array

current_number

而不是Sna

  • 评论!:编程的另一个非常重要的部分(注意:不是编码(。
    你在编码吗?
Don't care if anyone understands it or not, just doing it cause they said so.

还是编程?

Making a clear, maintainable and debuggable code.

你决定!

由于这个问题被标记为C++,我想给出一个额外的答案,它使用C++,尤其是现代C++算法。我还在代码中添加了注释,并使用了有意义的变量名称。我建议您将来尝试这样做。

示例代码在做什么?

首先,它会通知用户有关软件的信息,并询问应检查和添加多少值。这些值将存储在std::vector中。通过std::copy_nstd::istream_iterator,我们读取用户给出的值。std::istream_iterator只是在复制循环中调用提取器运算符>>

然后我们调用子函数来计算总和并将其显示给用户。

该子函数由一个 Lampda 定义和一个std::accumulate语句组成。就这样。

lambda 将 int 转换为std::string,然后检查数字中的任何字符是否小于"5"。然后它返回一个反转结果。

所以,你看,有了C++,实现变得非常简单:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
int sumOfNumbersWithDigitsGreaterThan5(const std::vector<int>& v) {
// Create a lambda that checks, if all digits are greater than 5
auto check5 = [](const int i) -> bool { std::string s{ std::to_string(i) };
return !std::any_of(s.begin(), s.end(), [](const char c) { return c <= '5'; }); };
// Calculate the sume of all given values in the vector with all digits greater than 5
return std::accumulate(v.begin(), v.end(), 0, 
[&](const int init, const int i) { return init + (check5(i) ? i : 0); });
}
int main() {
// Inform the user, what to do
std::cout << "Sum of all numbers having all digits greater than 5nnHow many numbers to you want to sum?:  ";
// Get the number of values that we want to sum up. Check plausibility
if (int numberOfValuesToCheck{}; (std::cin >> numberOfValuesToCheck) && (numberOfValuesToCheck > 0)) {
// Create a std::vector for our values having the requested number of elements
std::vector<int> values(numberOfValuesToCheck);
// Read the requested number of elements from std::cin to the values vector
std::copy_n(std::istream_iterator<int>(std::cin), numberOfValuesToCheck, values.begin());
// Show result
std::cout << "nnThe sum for all numbers with all digits greater 5 is:  " <<
sumOfNumbersWithDigitsGreaterThan5(values) << "n";
}
else {
std::cerr << "nn*** Error: Wrong inputn";
}
return 0;
}

当然,还有许多其他可能的解决方案。