所以,我正在尝试编写一个程序,允许用户输入两个整数,然后输入一个运算符(加号或减号),并找到添加/减去这两个值的结果。
例如,如果用户键入:2 3 +
代码将显示:2 + 3 = 5
如果用户忘记添加加号或减号,则会出现一条错误消息invalid entry
。到目前为止,我只能制作一个接受两个单独编写的整数的程序,然后才进行添加。
#include <stdio.h>
int main() {
int integer1, integer2, sum; // Declare 3 integer variables
printf("Enter first integer: "); // Display a prompting message
scanf("%d", &integer1); // Read input from keyboard into integer1
printf("Enter second integer: "); // Display a prompting message
scanf("%d", &integer2); // Read input into integer2
sum = integer1 + integer2; // Compute the sum
// Print the result
printf("The sum of %d and %d is %d.\n", integer1, integer2, sum);
return 0;
}
答案 0 :(得分:4)
从用户处获取操作员并将其存储为char。然后将运算符与加号,&#39; +&#39;和减号进行比较,&#39; - &#39;。如果它匹配其中一个,请执行该操作。如果没有,请打印您的错误消息。
char operator;
if(operator == '+')
sum = integer1 + integer2;
else if(operator == '-')
sum = integer1 - integer2;
else
{
printf("Error");
return 0;
}
答案 1 :(得分:3)
您可以在一个 int integer1, integer2, sum;// Declare 3 integer variables
char oper;//this is where you read the operator as character
printf("Enter an expression: ");// Display a prompting message
// Read expression like 2+3,2 +3,2 + 3... from user
int res=scanf("%d %c%d", &integer1,&oper,&integer2);
//we expect 3 fields to be converted and assigned by scanf
if(res<3)//this will catch expressions like 2+h,...
{
printf("Input error");
return 1;
}
switch(oper)
{
case '+':
sum = integer1 + integer2;// Compute the sum
printf("The sum of %d and %d is %d.\n", integer1, integer2, sum);
break;
case '-':
sum = integer1 - integer2;// Compute the difference
printf("The difference of %d and %d is %d.\n", integer1, integer2, sum);
break;
default:
printf("Invalid entry");
}
语句中读取整个表达式,如2 + 3,然后比较运算符以确定要执行的操作。
android:screenOrientation="landscape"