[已解决]-这是一个非常简单的问题,但是为什么我总是得到1? [英] [Solved] - This is a very simple question but why am I always getting 1?

查看:56
本文介绍了[已解决]-这是一个非常简单的问题,但是为什么我总是得到1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑函数sum(n)= 1 + 1/5 +1/10 +…+ 1/5n.
编写sum(n)的非递归版本.用它来计算sum(100).
代码如下:

Consider the function sum(n)= 1+1/5 +1/10 +… +1/5n .
Write a nonrecursive version of sum(n). Use it to calculate sum(100).
Here''s the code:

#include <iostream>
using namespace std;
double suma (int   n);

void main ()
{ 
	int n;
	cout<<"Enter an integer n to calculate sum(n)= 1+1/5 +1/10 +… +1/5n  \n";
	cin>>n;
	cout<<"The sum ("<<n<<") is "<<suma(n)<<endl;
}
double suma (int a)
{
	int i, sum=0;
	for (i=1 ; i<=a; i++)
	{
		sum += (1/(5*i));
	}
	return sum+1;
}

推荐答案

7mesho写道:

sum + =(1 /(5 * i));

sum += (1/(5*i));



1除以5小于1.随着i的增加,您的数字越来越接近0,并且从0.2开始,并且因为您使用的是int而不是float或double,所以循环中的值被加到总和并保持四舍五入为0.您返回的是double,但是在使用int的方法内部,还需要在方法内部使用double.

如果您了解了如何使用调试器,并逐步完成了代码,那么这对您而言将是显而易见的.



1 divided by 5 is less than 1. As i increases, your number gets closer and closer to 0, and as it starts at .2, and because you''re using int and not float or double, the values in the loop that get added to sum keep getting rounded down to 0. You are returning a double, but inside the method you''re using int, you need to use double inside your method also.

If you learned how to use the debugger, and stepped through your code, this would have been apparent to you in no time.


这篇关于[已解决]-这是一个非常简单的问题,但是为什么我总是得到1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆