-4

I'm new to programming and I'm working on a code that computes a sum of series based on two inputs (x and n)

enter image description here

Here is what I have so far:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int k,n;
    double x, sn=0;
    cout<<"enter n:";
    cin>>n;
    cout<<"enter x:";
    cin>>x;
    for(k=1;k<=n;k++)
    {
        sn+=(pow(-1, (1+k)))*((pow(x, k))/k);
    }
    cout<<sn;
    cout<<endl;
    return 0;
}

I'm not sure if I have some fundamental error in my code or there is an error in the mathematical expression. I keep getting 0

RandomJoe
  • 5
  • 5
  • what type of series?? – Rajeev Singh Apr 29 '17 at 08:07
  • @RajeevSingh See the formula at the beginning of the question. – Barmar Apr 29 '17 at 08:07
  • Don't post code as images... include it in question!! – Rajeev Singh Apr 29 '17 at 08:08
  • 4
    @randomJoe - Please do not edit the question in such a way that answers do not make sense – Ed Heal Apr 29 '17 at 08:13
  • code looks fine now!! – Rajeev Singh Apr 29 '17 at 08:14
  • If your code still only outputs `0` even after making (and testing?) the changes I suggested, then I would ask what are your inputs? Does your test input happen to consist exclusively of something that would either underflow or otherwise result in odd numerical results? – Travis Apr 29 '17 at 08:14
  • What version of C++ are you using? Casting shouldn't be necessary since `pow` returns a `double` and there is no `int`–`int` division in your formula. (although if that fix works, don't let me stop you from using it!) – Travis Apr 29 '17 at 08:17
  • @RandomJoe why do you keep deleting your comments? – Travis Apr 29 '17 at 08:19
  • 1
    really sorry - still new to the site and struggling. I think the reason the code didn't run properly was because of the math expression itself. After specifying that both part of the multiplication are doubles the output is correct. – RandomJoe Apr 29 '17 at 08:27
  • 1
    Read http://floating-point-gui.de/ and consider starting with large `k` (because of precision issues), counting downwards – Basile Starynkevitch Apr 29 '17 at 08:33
  • 1
    RandomJoe, I would recommend *not* using ideone.com (as it appeared you were using) to run this code. You don't know how it is being compiled. On a different note, check out the comment by @BasileStarynkevitch . The vagaries of floating-point arithmetic has tripped up many a programmer, and his recommendation is really quite on-point here. – Travis Apr 29 '17 at 08:41
  • RandomJoe, it also bears mentioning that if the numbers you are using really could lead to underflow even with a `double`, then you might want to consider using a `long double`. Although for a simple homework assignment, I doubt that's necessary... – Travis Apr 29 '17 at 08:48
  • 2
    If you say that you "keep getting 0", then you also have to tell us with which input you are getting that result. – Christian Hackl Apr 29 '17 at 09:06

2 Answers2

1

Change main() to int main(). C++ requires a type specifier for all functions (especially main).

To be honest, I'm not sure how you got it to compile without that.


Just as an additional "fyi", you could also make these two changes (but they're not necessary):

  1. Change main() to int main(int argc, char const *argv[]). That's the full function header for main, and it's what allows you to process command line arguments. Your program doesn't take any command line arguments though, so in this case a simple int main() is clearer (and thus preferable).

  2. Put return 0; as the very last line in your main function body. Whatever value your program returns when it concludes is what lets the operating system know whether your program succeeded or failed somehow. Technically, C++ will implicitly return 0 for you anyway if you don't do anything else and your program terminates normally. Still-and-yet, it's considered good style in some circles to explicitly return 0; (or to #include <stdlib.h> and return EXIT_SUCCESS;) rather than to let a returning function fall off the end of the block.


EDIT:

In response to your edits and comments, the problem probably lies elsewhere. I would strongly suggest looking at the link in the comment to your question by Basile Starynkevitch. Floating-point arithmetic can be a tricky thing to get right.

Additionally, please state what input values you are using. This is a general practice anyway for whenever you are asking other people for help, but in this case it is especially important due to the aforementioned issues with floating-point arithmetic.

Community
  • 1
  • 1
Travis
  • 2,135
  • 17
  • 29
  • Dare to explain the downvote? Especially after the question was (apparently) surreptitiously edited since I posted this answer? – Travis Apr 29 '17 at 08:11
  • My bad! Even without casting it works! :-) – kiner_shah Apr 29 '17 at 08:18
  • That does not answer the question at all. `main()` compiles with gcc (sort of extension, sort of legacy compatibility with C). `int main()` is enough. I am not sure about `char const *argv[]`. Standard does not say anything about `const` being there. – Zereges Apr 29 '17 at 08:30
  • 1
    @Zereges The question (and example code) has been heavily edited since I posted my answer. Moreover, `g++` is the proper command to compile C++, and it give an error trying to compile `main()` within the `int`. As you yourself said, the fact that `gcc` compiles just `main()` is no more than a "sort of extension, sort of legacy compatibility" thing. – Travis Apr 29 '17 at 08:37
  • Using anything other than `int main()` if you don't need to parse the command line arguments is bad style or at least redundant; the answer also incorrectly claims that a redundant `return 0` is "good practice". On top of that, it doesn't even try to answer the question. – Christian Hackl Apr 29 '17 at 09:02
  • @ChristianHackl That's why my primary answer advised using just `int main()`. Note that I only elaborated in a separate section below that on the option of using full header with command line parameters in order to provide additional "fyi" -style general knowledge. As for contesting my little bit about `return 0` being factually "incorrect," that is juvenile, if I may be blunt. It is clearly a matter of style (and a style [that has positive support](http://stackoverflow.com/a/8868139/5029307) too), and even then I still clarify that why it's not even necessary. Don't make this a flame war. – Travis Apr 29 '17 at 09:12
  • @Travis: Your answer *literally* tells the OP not to use `int main()` and to add `return 0;` and makes it clearly sound as if not doing so would be questionable. You are advocating your very personal style as if this was a widely accepted convention (which is far from the truth) and do not answer the question, hence the downvote. I think you have misunderstood the answer by Keith Thompson. He mainly talks about how using the macros is better than using 0 or some magic number *if* you need an explicit return value. His advice about returning 0 anyway is only related to C (for whatever reason). – Christian Hackl Apr 29 '17 at 09:21
  • 1
    @ChristianHackl My answer *literally* tells the OP to use `int main()`. And my answer *explicitly* says that using `return 0;` is not necessary (and is quite clearly just an additional bit of "fyi" info for a new programmer besides). Moreover, you are *blatantly* mischaracterizing my bit about `return 0;` as "advocating" for an unheard of style. As *clearly* indicated in my answer I am just providing a little additional info about a language feature *(and even saying it's use isn't necessary!)*. And the fact that someone else recommends it **proves** it is not some "personal" style. – Travis Apr 29 '17 at 09:29
  • Whether or not *you* use `return 0;` is none of my business. Moreover, I *never* say that it is a "widely accepted convention." I even explain how `return 0;` is *not* necessary, and *explicitly* state that it's just "style" anyhow (rather than calling it a formal convention of any type). If you have different opinions about that style, that's cool. But please don't misconstrue my comments, personally disparage me, and flame this comment thread just because you have a different opinion on a *minor* point of style. Just adding a comment about your style recommendation would be sufficient. – Travis Apr 29 '17 at 09:39
  • @Travis: Now seriously, you are taking this downvote *awfully* personally. Nobody flames or personally disparages you. With your recent edits, I'm still not entirely happy with the answer, but it no longer warrants a downvote, which is why I've removed mine. – Christian Hackl Apr 29 '17 at 09:45
0

Remove the expensive pow function

I.e.

double xk = 1;
for(k=1;k<=n;k++)
{
   xk *= x;
   if (k%2 == 0) { // k is even -> -1 ^ (1+k) = -1 * -1^even number = -1
    sn -= xk/k;
   } else {
    sn += xk/k;
   }
}

PS: This should be a comment - but comments make the code unreadable

Ed Heal
  • 59,252
  • 17
  • 87
  • 127