如何查找数字大于 5 的数字总和
How to find the sum of numbers that have digits higher than 5
所以我想写一个函数,返回数组中数字大于 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
...
使用- 更好的命名:不要使用
S
,a
和n
,除非它们非常清楚。digit
是一个不错的选择,所以要归功于这一点!
在这里,最好使用:
sum_of_special_numbers
和
array
和
current_number
而不是S
,n
和a
。
- 评论!:编程的另一个非常重要的部分(注意:不是编码(。
你在编码吗?
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_n
和std::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;
}
当然,还有许多其他可能的解决方案。
- 查找最接近的大于当前数字的数字的索引
- 如何找到大于整数的最小数字
- 如何查找数字大于 5 的数字总和
- 为什么 CSpinButtonCtrl 不能正确处理大于 1000 的数字?
- 计算向量中大于数字的元素
- 如何在向量中找到大于某些数字的所有元素
- 如何在给出前两个数字的级数中找到大于 x 的第 n 个最小子数组总和?
- 显示用户输入的平均数大于 50 和所有可被 3 整除的数字的乘积
- 如何在数字大于类型 size_t 的最大数量时使用 std::bitset
- 如何将一个数字(大于8个字节)从字符阵列转换为其ASCII表示
- 如何生成数字,直到它们大于10 000
- C 用户输入4个数字,并且该程序检查它们大于少于
- 为什么此代码只能识别文本文件中的第一行?输入任何大于 1 的数字都会返回"Atomic Number Not Found"
- 给定一个数字n,打印序列中大于或等于n的第一个数字
- bignumber.h arduino如何解析大于10位数字的数字
- 使用单个堆栈的中缀到后缀不适用于大于 9 的数字
- 在字符串中的一行中搜索大于0的数字
- 从字符串转换为数字大于 std::numeric_limit<double>::d igits10 的双精度
- 在C++中打开一个数字大于9的COM端口
- 检查数字是否为完全平方数(数字大于15位)