getchar/putchar のみを使用する単純な電卓を C で作成する必要があります。ユーザー入力をエコーしてから、数学演算を実行する必要があります (+、/、%、*、および - のみを使用する必要があります)。今のところ、値を入力変数に格納する限り、私は自分が間違っていることだけを気にしています。プログラムの残りの部分は、自分で簡単に実行できるはずです。
while ループでは、"else if" 内でのみ if/else を (主にエラー チェックの目的で) 入れ子にすることに注意しました。ループでスペースを無視してから、数値、数学演算子、およびその他の数値をそれぞれ input1、input2、および input3 に割り当てます。現在、「55 * 66」のようなものを入力すると、「* 0」のようなものが返されます。
ご覧いただきありがとうございます。
更新 (2014 年 3 月 22 日): 少し近づいています。私の問題は、各数値とオペランドの後に 1 つのスペースを入力した場合にのみプログラムが機能することです (つまり、「2 + 4」は機能しますが、スペースのないものや複数のスペースがあるものは機能しません)。また、数値を出力するために数値を入力する方法もよくわかりませんでした。私は printf を使用したので、その間に少なくとも動作するプログラムを作成できました。ありがとう。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int add(int input1,char operand, int input2);
int subtract(int input1,char operand, int input2);
int mod(int input1,char operand, int input2);
int multiply(int input1,char operand, int input2);
int divide(int input1,char operand, int input2);
int main()
{
int answer = 0;
int ch = 0;
int input1 = 0;
char operand = 0;
int input2 = 0;
int function = 0;
printf("\nPlease enter a calculation to be made.\n");
while (((ch = getchar()) != ' ') && (ch != '\n')){
if (ch == '-') {
printf("\nError: no negatives allowed.\n");
}
else if (!isdigit(ch)){
printf("\nError: number not inputted (first number).\n");
}
else {
input1 = (input1 * 10) + (ch - '0');
}
}
while (((ch = getchar()) != ' ') && (ch != '\n')){
switch(ch){
case '+':
operand = '+';
break;
case '-':
operand = '-';
break;
case '%':
operand = '%';
break;
case '*':
operand = '*';
break;
case '/':
operand = '/';
break;
default:
printf("Error: input is not one of the allowed operands.");
break;
}
}
while (((ch = getchar()) != ' ') && (ch != '\n')){
if (ch == '-') {
printf("\nError: no negatives allowed.\n");
}
else if (!isdigit(ch)){
printf("\nError: number not inputted (second number).\n");
}
else {
input2 = (input2 * 10) + (ch - '0');
}
}
printf("%d", input1);
putchar(' ');
printf("%c", operand);
putchar(' ');
printf("%d", input2);
putchar(' ');
putchar('=');
putchar(' ');
if (operand == '+'){
answer = add(input1, operand, input2);
printf("%d", answer);
}
else if (operand == '-'){
answer = subtract(input1, operand, input2);
printf("%d", answer);
}
else if (operand == '%'){
answer = mod(input1, operand, input2);
printf("%d", answer);
}
else if (operand == '*'){
answer = multiply(input1, operand, input2);
printf("%d", answer);
}
else if (operand == '/'){
answer = divide(input1, operand, input2);
printf("%d", answer);
}
return 0;
}
int add(int input1,char operand, int input2){
return input1 + input2;
}
int subtract(int input1,char operand, int input2){
return input1 - input2;
}
int mod(int input1,char operand, int input2){
return input1 % input2;
}
int multiply(int input1,char operand, int input2){
return input1 * input2;
}
int divide(int input1,char operand, int input2){
return input1/input2;
}