我正在學習使用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的值未定義在那點所以總和的價值是垃圾。 –