【问题标题】:Intro to C: Addition and PrintingC 简介:加法和打印
【发布时间】:2013-04-17 07:57:33
【问题描述】:

我正在尝试制作一个可以执行各种算术函数的基本计算器,从加法开始!现在我已经弄清楚了它的基本逻辑,但我不确定如何获取两个输入并打印出来!

#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. */
              ;
    }
    }        

【问题讨论】:

  • 你首先要做的是找出不同的输入方法。最常用的一个(对于初学者)是scanf。然后,您必须阅读scanf's manual。当您了解如何使用scanf 时,开始编码。
  • @Andrew Hu - 不要忘记接受已经解决了您的问题/问题的答案 :)

标签: c printf calculator addition


【解决方案1】:

使用 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) );
            }
    

    【讨论】:

    • 我会删除 cmets 以缩短答案。但是+1。
    • 使用 lf 比使用 f 有优势吗? lf 是 64,f 是 32,所以更精确?
    • %lf 能够读取double-values,而%f 读取“普通”float-values。因此,根据您的意愿,您可以互换它们。
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2014-03-09
    • 2015-06-16
    • 1970-01-01
    • 2018-04-17
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多