现在我正在通过阅读 Stephen Kockan 的《C 语言编程,第三版》一书来学习 C 语言编程。 书上的Exercise6-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 运算符告诉程序执行是 结尾。对内容进行算术运算 累加器,其中包含作为第二个键入的数字 操作数。
Here is a link ,我也是怎么想出来的。
不幸的是它是在 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()
函数,以及读取操作值和累加器值。因为这两件事可能不一样。
最佳答案
这是您的 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;
}
关于c - 练习6-4 C 语言编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17444522/