我想學C++,而我纔剛剛開始,但我已經寫了下面的:似乎無法輸出小數
#include "stdafx.h"
#include <iostream>
#include <iomanip> // for setPrecision()
#include <cmath>
int getVal()
{
using namespace std;
int value;
cin >> value;
return value;
}
char getChar()
{
using namespace std;
char mathOperator;
cin >> mathOperator;
return mathOperator;
}
double doCalc(int a, int b, char mO)
{
using namespace std;
cout << a << mO << b << " = ";
double result;
switch(mO)
{
case '+': result = a+b; break;
case '-': result = a-b; break;
case '*': result = a*b; break;
case '/': result = a/b; break;
}
cout << setprecision(20);
cout << result << endl;
return result;
}
bool isEven(double x)
{
if(fmod(x,2)) {
return false;
} else {
return true;
}
}
int main() {
using namespace std;
cout << "Playing with numbers!" << endl << endl;
cout << "Enter a value: ";
int a = getVal();
cout << "Enter another value: ";
int b = getVal();
cout << "Enter one of the following: (+, -, *, /)";
char mathOperator = getChar();
double result;
result = doCalc(a,b,mathOperator);
switch(isEven(result))
{
case true: cout << "Your number is even." << endl; break;
case false: cout << "Your number is odd." << endl; break;
}
return 0;
}
這很簡單,我知道,但由於某種原因在函數doCalc()我似乎無法輸出小數位。我用setprecision,但沒有區別。我測試的數字是100/3,應該是33.33333333333333333333333333。我只是得到33.
有誰能告訴我爲什麼?
INT/INT總是給你一個int回來。嘗試在計算之前進行雙擊/浮動。 – Ra1nWarden 2014-08-31 14:27:32
用int除int會給我一個int嗎? – Chud37 2014-08-31 14:28:19
請閱讀[最小示例](http://stackoverflow.com/help/mcve)。 – 2014-08-31 14:28:20