-4

现在我正在通过阅读 Stephen Kockan 的“Programming in C, 3rd edition”一书来学习用 c 编程。书里的练习6-4真是让我头疼。书中说:

Write a program that acts as a simple "printing" calculator. 

The program should allow the user to type in expressions of the form

数字运算符

程序应识别以下操作员:

 '+'  '-'  '*'  '/'  'S'  'E'

S 运算符告诉程序将“累加器”设置为输入的数字。E 操作符告诉程序执行结束。对累加器的内容执行算术运算,键入的数字作为第二个操作数。

这是一个链接,我也是如何弄清楚的。

不幸的是,它在 Objective-C 中(但仍然是相同的练习!),而且我不理解 Objective-C 语法。

更新

这是我到目前为止所做的:

// "Printing" Calculator

#include <stdio.h>

int main(void)
{
    char  operator;
    float value, result, accumulator;

    printf("Begin Calculations...\n\n");

    operator = '0';

    while ( operator != 'E')
    {
        scanf("%f %c", &value, &operator);
        switch(operator)
        {
            case 'S':
                accumulator = value;
                printf("The accumulator = %f", accumulator);
                break;
            case '+':
                result = accumulator + value;
                printf("%f + %f = %f", accumulator, value, result);
                break;
            case '-':
                break;
            case '*':
                break;
            case '/':
                break;
            default:
                printf("Unknown operator");
                break;
        }
    }

    printf("Calculations terminated");

    return 0;
}

我不知道如何使用该scanf()函数,并读取操作的值和累加器的值。因为这两件事可能不一样。

4

1 回答 1

0

这是你的 C 代码。

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

int main (void) 
{ 
    int loop; 
    float value, 
    acc = 0; 
    char o;
    printf ("Simple Printing Calculator Program\n\n"); 
    printf ("\nKEY: \n+ Add \n- Subtract \n* Multiply \n/ Divide\n"); 
    printf ("S Set Accumulator \nE End Program\n\n"); 
    printf ("Enter a number and an operator, then press enter\n\n"); 
    printf ("Type in your expression: ");
    for ( loop=0 ; loop>-1; ++loop)
    {
        {
        scanf ("%f %c", &value, &o);
        if ( o == '+' )
        { 
            acc = acc + value; printf ("\n%.2f\n",acc); 
        }
        else if ( o == '-' )
        { 
            acc = acc - value; printf ("\n%.2f\n",acc); 
        }
        else if ( o == '*' )
        { 
            acc = acc * value; printf ("\n%.2f\n",acc); 
        }
        else if ( o == 'S' )
        { 
            acc = value; printf ("\n%.2f\n",acc); 
        }
        else if ( o == 'E' )
        { 
            printf ("\nFinal Value: %.2f\n\nGoodbye!",acc); loop = loop + 1000; 
        }
        else if ( o == '/' ) 
            if ( value == 0 )
            { 
                loop = loop - loop -100; 
                printf ("\nDivision by zero.\n"); 
            } 
            else
            { 
                acc = acc / value; printf ("\n%.2f\n", acc); 
            } 
        else
        { 
            loop = loop -loop-100; 
            printf ("\nUnknown operator.\n"); 
        }
    }
    getch (); 
    return 0; 
}
于 2013-07-03T10:13:18.067 回答