我试图在一个for循环中编写两个循环,所以我在for循环中查找了多个变量的语法
问题是第二个变量l
没有更新,我不知道为什么
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=100000000;
for (v, l ; v<= 100000000, l >= 1 ; v++, l--)
{
vsum= vsum + 1/v;
nsum= nsum + 1/v;
lsum= lsum + 1/l;
msum= msum+ 1/l;
}
cout << " The float sum of all numbers 1 through 1/100000000 is " << vsum << endl;
cout << " The double sum of all numbers 1 through 1/100000000 is " << nsum << endl;
cout << "The float sum of all numbers 1/100000000 through 1/1 is " << lsum << endl;
cout << "The double sum of all numbers 1/100000000 through 1/1 is " << msum << endl;
cin >> vsum;
}
我想你的问题是
float f = 100000000;
为什么--f;
离开f
不变?
答案是由于的粒度float
。的float
精度不足以存储每个可能的整数。显然,例如32位浮点数不能存储与32位int一样多的整数值。
距离0
越远,a的连续可能值之间的差距就越大float
。在您的系统上,100000000 - 1
它仍然大于float的下一个可能值100000000
。
C ++的规则是,当计算结果不能精确地用浮点数表示时,则由实现决定使用下一个最低值还是第二个最高值。(因此,您的编译器应实际记录此处发生的情况)。在这种情况下,您的系统使用的是第二高的值。
为了让您的预期效果,化妆v
和l
有整型,并在实际计算中做了浮充转换,如
vsum += 1.f/v;
nsum += 1.0/v;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句