[英]C++, constructing a program that reads two real numbers and a character
我正在尝试编写一个程序,该程序能够读取两个实数,然后再读取用户输入的字符。 然后程序将通过字符评估两个数字。 角色可以是我在下面列出的任何角色:
1. +(加法)
2.-(减法)
3. *(乘法)
4. /(部门)
5.%(剩余)
下面我发布了我编写的代码,用于检查打印出的值是否正确:
#include<stdio.h>
int main(){
float a,b,add,subtract,division,multiply,remainder;
char op;
printf("Enter two real numbers followed by one these characters:+, -, *, /, or % : ");
scanf("%f%f %c",&a,&b,&op);
printf("%.1f %c %.1f\n",a,op,b);
if (op=='+'){
add = a + b;
printf("%f",add);
}
else if (op=='-'){
subtract=a-b;
printf("%f",subtract);
}
else if (op=='/'){
division=a/b;
printf("%f",division);
}
else if (op=='*'){
multiply =a*b;
printf("%f",multiply);
}
else if (op=='%'){
remainder=a%b;
printf("%f",remainder);
}
else{
printf("invalid symbol");
}
return 0;
}
谁能告诉我为什么我遇到运行时错误?
注意: OP在回答了最初的问题后已大大改变了该问题,而这正是本文所关注的内容,因此,下面的答案目前看来已完全偏离目标。
如果有人能解释为什么我看到不同的价值观,将不胜感激。
您的代码有多个问题。
float
类型,但是它将它们转换为int
。 您的scanf
应该使用"%f %f %c"
代替实数而不是整数 。 2 2 +
,但是您的scanf
表示"%d%d %c"
(注意格式字符串中的空格与输入中的多余空间) printf
函数调用需要将参数交换为printf("%f %c %f",a, op, b);
(注意格式字符串使用"%f"
以及op
和b
变量的取反) 第一点基于用户的打印文本,要求“真实”数字。
第二点和第三点是罪魁祸首,因为当您在提示符下输入2 2 +
时,变量外观为a = 2
, b = 2
和op = 43
,这是'+'
字符的数值。
然后,当您打印它时,最终将'+'
字符解释为整数,而得到的却是43
。
程序的固定版本如下:
#include<stdio.h>
int main(){
float a, b, result;
char op;
printf("%s", "Enter two real numbers followed an operator (+, -, *, /, %): ");
scanf("%f %f %c", &a, &b, &op);
switch(op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
/* make sure b != 0 */
result = a / b;
break;
case '%':
/* make sure b != 0 */
/* we type-cast to int because modulus is not defined for floats */
result = (float)((int)a % (int)b);
break;
default:
printf("%s\n", "Unknown operation");
break;
}
printf("%f %c %f = %f",a, op, b, result);
return 0;
}
其用法和输出:
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 5 +
5.000000 + 5.000000 = 10.000000
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 5 *
5.000000 * 5.000000 = 25.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 5 /
5.000000 / 5.000000 = 1.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 10 5 %
10.000000 % 5.000000 = 0.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 10 %
5.000000 % 10.000000 = 5.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 8 5 -
8.000000 - 5.000000 = 3.000000
问题在于您的打印方式。 您正在尝试将数字打印为char和将char打印为数字:
printf("%d %c %d",a,b,op);
我想你的意思是:
printf("%d %d %c",a,b,op);
因此,这只是打印b的ASCII值,这将为您提供一个有趣的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.