2013-04-17 60 views
1

我正在试着制作一个基本的计算器,它可以执行各种算术功能,从添加开始!现在我已经掌握了它的基本逻辑,但我不确定如何接受两个输入并将其打印出来!C语言简介:添加和打印

#include <stdio.h> 

int main() 
{ 
    char mychar; 
    int a; 
    int op1; 
    int op2; 

    printf("Welcome to Andrew Hu's calculator program!\n"); //Greeting 

    while(1) 
    { printf("Enter a mathematical operation to perform:\n"); 
     scanf("%c", &mychar); 

    if(mychar == '+') //Valid Operators 
     a = 1; 
    else 
     a = 0; 


    if(a == 0) //Operator Checker, error if invalid 
     printf("\nError, not a valid operator\n"); 
    else if(a == 1){ 
     printf("%c\n", &mychar), 
     printf("Enter OP1:\n"), 

     /* not sure what to put here to echo the character as a decimal*/ 

     printf("Enter OP2:\n"), 

     /* not sure what to put here to echo the character as a decimal either*/ 

     printf("Result of %d %c %d = %d\n", op1, mychar, op2, (op1 + op2)) 
     /* this last line I'm not too sure of. I'm trying to print out the expression 
      which is op1 + op2 = the sum of both. */ 
       ; 
    } 
    }   
+0

你首先要做的是找出不同的输入方法。最常用的(初学者)是'scanf'。然后,您必须阅读['scanf'手册](http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html)。当您了解如何使用scanf时,开始编码_only_。 –

+1

@Andrew Hu - 不要忘记接受答案,已经解决了你的问题/问题:) –

回答

5

使用scanf语句获取输入,就像采用数学运算符一样。一个switch case语句可以很好地实现计算器。

scanf(" %d",&op1); 
2

使用scanf功能在一个浮点值来读取像

double op1 = 0.0; 
scanf("%lf", &op1); 

%lf表示读取输入值作为float - 值。

当您在命令行中输入值时,它们将显示。

else if(a == 1){ 
    printf("%c\n", mychar), // don't use & with printf as it will print the address of mychar 
    printf("Enter OP1:\n"), 

    double op1 = 0.0; 
    scanf("%lf", &op1); 

    printf("Enter OP2:\n"), 

    double op2 = 0.0; 
    scanf("%lf", &op2); 

    if(a == 1) 
     printf("Result of %lf + %lf = %lf\n", op1, op2, (op1 + op2)); 
     } 
+0

我想删除评论以使答案稍微短一些。但+1。 –

+0

感谢您的提示! –

+0

在f上使用lf有没有优势?如果是64和f是32,那么更精确? –