2011-11-16 76 views
0

我需要确定一组输入的标准偏差。这需要(每个输入 - 均值)^ 2的总和。我有以下代码来执行此操作(510是测试的示例输入):整数转换为双重

int testDiff = 510;  
console.printf("testDiff = %i \r\n",testDiff); 

double testDiff_double = static_cast<double>(testDiff); 
console.printf("testDiff_double = %d \r\n",testDiff_double); 

double result = pow(static_cast<double>(testDiff),2); 
console.printf("result = %d \r\n",result); 

但是,此代码不会生成期望的输出(260100)。如果我打印在每个阶段获得的值,我会得到以下内容:

testDiff = 510 
testDiff_double = 0 
pow = 0 

为什么从整数转换为双失败?我正在使用static_cast,因此如果转换出现逻辑问题,我期望在编译时发生错误。

注意(虽然它应该没关系):我在MBED微控制器上运行此代码。

+0

或者使用C++流,因为它会避免这样的错误,并做正确的事,因为编译器会选择如何打印类型。 –

+0

%d - >%f,%d是整数。 – Ylisar

+0

不相关,但你可能会感兴趣:你计算标准偏差的方式有准确性问题,结帐这个http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance – Monkey

回答

2

因为您使用的是%d而不是%f来显示浮点值。

+0

是的 - 那样做。我应该在深夜停止工作。我在编程时处理“数学”这么少,我忘了它是%f而不是%d ... – BSchlinker

2

在您的printf函数中,请尝试使用%f而不是%d。

1

您必须使用%f%e%E%g以显示双/浮点数。

printf reference page

c Character 
d or i Signed decimal integer 
e Scientific notation (mantise/exponent) using e character 
E Scientific notation (mantise/exponent) using E character 
f Decimal floating point 
g Use the shorter of %e or %f 
G Use the shorter of %E or %f 
o Unsigned octal 
s String of characters 
u Unsigned decimal integer 
x Unsigned hexadecimal integer  
X Unsigned hexadecimal integer (capital letters) 
p Pointer address 
n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored. 
% A % followed by another % character will write % to stdout.