C语言 在 C 中使用 switch 和函数的计算器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18393525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:13:54  来源:igfitidea点击:

Calculator using switch and functions in C

cfunctionswitch-statementcalculator

提问by confusedcat

This is our exercise today and our first time coding call functions in class. These are the instructions given to us:

这是我们今天的练习,也是我们第一次在课堂上编写调用函数。这些是给我们的指示:

  1. I have to make a C Program calculator with choices: 0 - exit, 1 - add, 2 - subtract, 3 - multiply and 4 - divide.
  2. Once the user inputs their choice, I ask for two numbers from them.
  3. I need to use functions for each arithmetic operation.
  4. When I'm done with calculating, it should go back to the menu.
  5. The program only ends when the user chooses 0.
  1. 我必须制作一个带有选项的 C 程序计算器:0 - 退出,1 - 加,2 - 减,3 - 乘和 4 - 除。
  2. 一旦用户输入他们的选择,我就会向他们询问两个数字。
  3. 我需要为每个算术运算使用函数。
  4. 当我完成计算后,它应该回到菜单。
  5. 程序仅在用户选择 0 时结束。

This my program that I've edited a lot already.

这是我已经编辑了很多的程序。

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

int add(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);

int main(){
int num1, num2, choice;

printf("[0] Exit\v[1] Add\v[2] Subtract\v[3] Multiply\v[4] Divide");
scanf("%d", &choice);

switch(choice){
    case 0:
        return 0;
        break;
    case 1:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d", add(num1,num2));
        break;
    case 2:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d ", sub(num1,num2));
        break;
    case 3:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d", mul(num1,num2));
        break;
    case 4:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d", div(num1,num2));
        break;
    default:
        printf("That is not a valid choice.");
        break;
}
    //Addition
int add(int x,int y){
    int z = x + y;
    return z;
}   
//Subtraction
int sub(int a,int b){
    int c = a - b;
    return  c;
}   
//Multiplication
int mul(int d,int e){
    int f = d * e;
    return f;
    }
//Division
int div(int g,int h){
    int i = g / h;
    return i;
}
}

For now, it's down to two errors only: [Error] conflicting types for 'div' and previous declaration of 'div' was here

现在,它只归结为两个错误:[Error] 'div' 的类型冲突和先前的 'div' 声明在这里

回答by Thi Nguyen

"I've already edited it, but I always get this error: [Error] conflicting types for 'div' "

“我已经编辑过它,但我总是收到这个错误:[错误] 'div' 的类型冲突”

=> because the function name div() already defined in stdlib.h.

=> 因为函数名 div() 已经在 stdlib.h 中定义了。

You should rename it by another name.

你应该用另一个名字重命名它。

e.g: Divide(int, int);

例如: Divide(int, int);

回答by darmat

One basic principle of programming is D.R.Y. = Don't Repeat Yourself. If you see the same code repeated in the same way in multiple spots then it means that you could group it in a nice function. You could save some space by not allocating a variable in each math function, simply return the math formula.

编程的一项基本原则是 DRY = 不要重复自己。如果您在多个位置看到相同的代码以相同的方式重复,则意味着您可以将其分组为一个不错的函数。您可以通过不在每个数学函数中分配变量来节省一些空间,只需返回数学公式即可。

Also, if this is meant to be a continuous cycle, you should probably use a loop such

此外,如果这是一个连续的循环,您可能应该使用这样的循环

while(true) {
...
}

and exit if the user types 0

并在用户输入 0 时退出

回答by Amarnath Krishnan

You function declaration should be outside the main function. So close the main function, than define add, sub, mul, div. It will resolve the errors. Use looping to do some process again and again. To avoid code redundancy, you can create a function that gets the input values and store it in memory address. Call this function wherever you want instead of repeating codes.

你的函数声明应该在主函数之外。所以关闭main函数,而不是定义add,sub,mul,div。它将解决错误。使用循环一次又一次地做一些过程。为了避免代码冗余,您可以创建一个函数来获取输入值并将其存储在内存地址中。在任何你想要的地方调用这个函数,而不是重复代码。

Below you can find a function name getDatawhich gets two values from user and stores it in the memory address passed to that function. The calling program will pass the memory address where those values has to be stored.

您可以在下面找到一个函数名getData,它从用户那里获取两个值并将其存储在传递给该函数的内存地址中。调用程序将传递必须存储这些值的内存地址。

Some Guidelines while writing code:

编写代码时的一些准则:

1.) Write DRY(Dont Repeat Yourself) type code.
2.) Use only required header files. stdio.h is enough to do basic programming in your case.

Simple Working code:

简单的工作代码:

#include<stdio.h>

// Function Prototype
int add(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);
void getData(int *, int *);

// Main Function
int main()
{
    int num1, num2, choice;
    while(1)
    {
      printf("\n[0] Exit\n[1] Add\n[2] Subtract\n[3] Multiply\n[4] Divide\nEnter Your Choice:");
      scanf("%d", &choice);
      switch(choice)
      {
         case 0:
           return 0;
         case 1:
           getData(&num1, &num2); // get Input Values
           printf("%d", add(num1,num2));
           break;
         case 2:
           getData(&num1, &num2); // get Input Values       
           printf("%d ", sub(num1,num2));
           break;
         case 3:
           getData(&num1, &num2); // get Input Values       
           printf("%d", mul(num1,num2));
           break;
         case 4:
           getData(&num1, &num2); // get Input Values
           printf("%d", div(num1,num2));
           break;
         default:
           printf("That is not a valid choice.");
           break;
      }
    }
}

// Get Memory Address of num1, num2 and store input values in those locations.
void getData(int *num1_ptr, int *num2_ptr)
{
printf("Enter 1st number:\n");
    scanf("%d", num1_ptr);
printf("Enter 2nd number:\n");
    scanf("%d", num2_ptr);
}

//Addition
int add(int x,int y)
{   return x+y;   }   

//Subtraction
int sub(int x,int y)
{   return  x-y;  }   

//Multiplication
int mul(int x,int y)
{   return x*y;   }

//Division
int div(int x,int y)
{   return x/y;   }

回答by mahmudul hasan sojib

#include<stdio.h>
#include<math.h>
int add(int, int);
int sub(int, int);
int mul(int, int);
float dib(float, float);

int main(){
int num1, num2, choice;

printf("1:addiction\n2:substraction\n3:multiplication\n4:division\n0:exit\nplease enter your choice:");
scanf("%d", &choice);

switch(choice){
    case 0:
        return 0;
        break;
    case 1:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d", add(num1,num2));
        break;
    case 2:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d ", sub(num1,num2));
        break;
    case 3:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%d", mul(num1,num2));
        break;
    case 4:
        printf("Enter 1st number:\n");
        scanf("%d", &num1);
        printf("Enter 2nd number:\n");
        scanf("%d", &num2);
        printf("%f", dib(num1,num2));
        break;
    default:
        printf("That is not a valid choice.");
        break;
}
        }

    //Addition
int add(int x,int y){
    int z = x + y;
    return z;
}
//Subtraction
int sub(int a,int b){
    int c = a - b;
    return  c;
}
//Multiplication
int mul(int d,int e){
    int f = d * e;
    return f;
    }
//Division
float dib(float g,float h){
    float i = g / h;
    return i;
}

回答by pablo1977

BTW, you have a syntax error. Your function main()looks like:

顺便说一句,你有一个语法错误。你的功能main()看起来像:

int main(void) {
   ...whatever...
   switch (choice) {
     ...whatever...
   }

int add() {
         ...
}

...whatever...

} /* wrong place for closing '}' (this closes the "main() {" block */

The result of your code is that the functions add(), sub(), etc., are defined inside the body of main(), which is wrong.

你的代码的结果是函数 add()、sub() 等都定义在 的主体内main(),这是错误的。

回答by Paul Evans

You've got a hugeproblem by coding:

您通过编码遇到了一个巨大的问题:

int sum = add; // etc

int sum = add; //

this doesn't make any sense -- you're assigning a function pointer (add) to an int(sum)

这没有任何意义——您将函数指针 ( add)分配给int( sum)

You simply want (later on in the code):

您只需要(稍后在代码中):

printf("%d\n", add(num1, num2);

you are making the code fartoo complex -- simplicity is good!.

你可以将这个代码太复杂-简单就是