2013-04-17 105 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,那麼更精確? –