【发布时间】:2012-06-13 11:55:29
【问题描述】:
我正在学习 C++ 编程的基础知识,我需要编写一个使用 if/else 语句执行一些基本数学函数的程序:减法、加法、乘法等。我没有收到任何编译或运行时错误,但我最终得到的值总是不正确的。
我改变了一些东西,试图看看我哪里出错了,但就文字而言,屏幕上打印的内容是正确的,而不是答案。例如,当我扫描 -(减号)作为输入时,它会读取 x 和 y 之间的差异是一个高得离谱的数字。
无论如何,这是我的代码,任何帮助将不胜感激!
/*
* This program performs some basic math calculations
*/
#include <stdio.h>
#include <math.h>
int main() {
int x,y;
float sum = x+ y;
float difference = x-y;
float product = x*y;
float quotient = x/y;
float exponent = x^y;
float modulus = x%y;
char symbol;
printf("What is the value of x?\n");
scanf("%d", &x);
printf("What is the value of y?\n");
scanf("%d", &y);
printf("What is your operator?\n");
scanf(" %c", &symbol);
if (symbol== '+')
printf("The sum of x and y = %f\n", sum);
else if (symbol=='-')
printf("The difference between x and y = %f\n", difference);
else if (symbol=='*')
printf("The product of x and y = %f\n", product);
else if (symbol=='/')
printf("x divided by y = %f\n", quotient);
else if (symbol=='^')
printf("x multiplied exponentially by y = %f\n", exponent);
else if (symbol=='%')
printf("x is this much percent of y =%f\n", modulus);
return 0;
}
【问题讨论】:
-
在 C 和 C++ 中,类似 "sum = x + y" 的东西是一个顺序执行的操作,而不是一个等式...... sum 立即接收一个值 x + y,但是 x 和y 那时没有定义,所以 sum 的值是垃圾。
标签: c++ c calculator