2014-08-31 34 views
0

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

有谁能告诉我为什么?

+4

INT/INT总是给你一个int回来。尝试在计算之前进行双击/浮动。 – Ra1nWarden 2014-08-31 14:27:32

+0

用int除int会给我一个int吗? – Chud37 2014-08-31 14:28:19

+1

请阅读[最小示例](http://stackoverflow.com/help/mcve)。 – 2014-08-31 14:28:20

回答

2

让我们来看看一些简单的代码:

std::cout << 4/3 << std::endl; // Outputs the integer 1 
std::cout << 4.0/3 << std::endl; // Outputs the double 1.3333333333 

整数/整数给出向零舍一个整数结果。

如果你传递一个浮点数或一个double(注意4.0,这是一个double),那么你会得到小数位。

你的具体情况,我建议:

case '/': result = static_cast<double>(a)/b; break; 

或:

case '/': result = (double) a/b; break; 
+1

我建议不要在C++中使用C脚本 – paulm 2014-08-31 14:34:35

+0

也许增加这个选项:'a * 1./b;' – nwp 2014-08-31 14:41:32