我想学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