C++/C++ code

Advertisement


Question
hello,

I wrote a function for a function that receives two integers, where (m < n) and returns the sum:

 (1/m) + (1/(m+1)) + (1/(m+2)) + ... + 1/n

here is the function

int sum( int m, int n )
{

  int total;
  if ( n = m )
     return 1/n;
  else
     return (1 / m) + sum( m + 1, n );
}

but unfortunately the code compiles but doesn't answer correctly, please help me locate the error.


Answer
Hi Ibrahim! I'm really sorry this took so long to answer. I'm not sure what kind of output you're getting, but I came up with an algorithm that works. I don't usually do this, but since I don't know specifically what you're getting, I'll just give you the working code:

#include <iostream>

using namespace std;

float sum(float m, float n);

int main()
{
  float m;
  float n;
  float total;

  cin >> m;
  cin >> n;

  total = sum(m,n);
  cout << endl << total;

  system("pause");
  return 0;
}

float sum(float m, float n)
{
  
  float total;
  if ( n == m )
  {
     total = (1/n);
     return total;
  }

  else
  {
     total = (1 / m) + sum( m + 1, n );
     return total;
  }
}

everything needs to be a float, or you'll get an answer of 0, so that might be part of it. If there's anything at all that isn't clear about that solution, please contact me, and I'll be happy to give you a hand.

Thanks for the question Ibrahim!

-Sean

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Sean Wcisel

Expertise

I can answer most beginner and intermediate level questions. My strengths are various algorithms and data manipulation. My background might be best suited to anything from basic CPP and file I/O, to algorithms involving recursion, hashing, binary search trees, and so on. I've done some tutoring in my free time, both online and in person. I also have quite a bit of debugging experience. I have some experience with game code, specifically using D3D based game engines. I only speak English, but I believe I do so very well :). I'm completely unable to answer questions about coding drivers for hardware, and many library specific issues.

Experience

I've studied CPP for roughly four years now, with a combined eight years of object oriented programming experience. I have worked professionally in the field for about a year. I have also had some tutoring experience in CPP and C#

Organizations
IEEE, Western Michigan University Computer Club

Education/Credentials
Western Michigan University

©2016 About.com. All rights reserved.