首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在计算函数中不重复代码?

如何在计算函数中不重复代码?
EN

Stack Overflow用户
提问于 2022-09-07 15:29:40
回答 3查看 67关注 0票数 1

我做了一个简单的程序,对给定数组的所有元素执行基本算术操作。但是问题是,代码是非常重复的,编写重复的代码并不是一个好的实践,我无法想出解决这个问题的方法。我们如何尽量减少这个程序中的代码重复?

代码语言:javascript
复制
int add(int numcount, int numarr[]){
    int total = numarr[0];

    // add all the numbers in a array
    for (int i = 1; i < numcount; i++){
        total += numarr[i];
    }

    return total;
}

int sub(int numcount, int numarr[]) {
    int total = numarr[0];

    // subtract all the numbers in array
    for (int i = 1; i < numcount; i++){
        total -= numarr[i];
    }

    return total;
}

int mul(int numcount, int numarr[]) {
    int total = numarr[0];

    // multiply all the numbers in array
    for (int i = 1; i < numcount; i++){
        total *= numarr[i];
    }

    return total;
}

int main(int argc, char* argv[]){
    const int n = 5;
    int arr[n] = {1, 2, 3, 4, 5};
    
    cout << "Addition: " << add(n, arr) << endl;
    cout << "Subtraction: " << sub(n, arr) << endl;
    cout << "Multiplication: " << mul(n, arr) << endl;
}
EN

Stack Overflow用户

发布于 2022-09-07 16:07:55

我们如何尽量减少这个程序中的代码重复?

这样做的一种方法是有一个char类型的参数,表示需要执行的操作,如下所示:

代码语言:javascript
复制
//second parameter denotes the operator which can be +, - or *
int calc(int numcount, char oper, int numarr[])
{
    //do check here that we don't go out of bounds 
    assert(numcount > 0);
    
    int total = numarr[0]; 

    // do the operatations for all the numbers in the array
    for (int i = 1; i < numcount; i++){
        total = (oper == '-') * (total - numarr[i]) + 
                (oper == '+') * (total + numarr[i]) + 
                (oper == '*') * (total * numarr[i]); 
                 
    }
    return total;
           
}
int main()
{
    int arr[] = {1,2,3,4,5,6};
    std::cout << calc(6, '+', arr) << std::endl; //prints 21 
    std::cout << calc(6, '-', arr) << std::endl; //prints -19
    std::cout << calc(6, '*', arr) << std::endl; //prints 720
  
}

工作演示

票数 -1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73638098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档