r/programminghelp • • Oct 14 '18

[C++] I'm trying to write a program that given a number and then the coefficients of a polynomial (from x^0 to x^n) gives the result of the polynomial when x=said number but it doesn't always work

Post image
4 Upvotes

7 comments sorted by

2

u/RamenRin Oct 14 '18

Specifically, it doesn't work if one of the coefficients is 0 like for example if the input is:

2

1 2 0 5

(It should say 45.0000 instead of 85.0000)

I know it's probably a dumb question but it's my first programming class and I'm bad at it lol. The program seems to work fine if the input is:

2

1 1 1

Or something like that, which is what confuses me.

Hopefully I was clear enough and someone can help me😅

2

u/icecapade Oct 15 '18

You have a math error, and it has nothing to do with the number of zeros. Here's a hint. What should

2
0 0 0 1

yield? What does it actually yield? What about:

2
0 0 0 0 1

You should notice a pattern here (after you examine the output), which, I hope, will make the issue more clear.

1

u/RamenRin Oct 15 '18

i get it now thanks! The problem is that the each ni should be ni-1 instead (right?) ill look into it tomorrow morning see if I can figure it out! Thanks a bunch

2

u/icecapade Oct 16 '18 edited Oct 16 '18

Not quite, but you're on the right track. Specifically, look at line 16 (n = n * n). Let's say that the user inputs some value x for n.

On the first iteration of the while loop, n = x. After line 16 of the first iteration, n is updated with n = n * n, so now, n = x * x = x2. After the second iteration of the while loop, n will be updated again, but since the value of n is x2, you end up with n = n * n = x2 * x2 = x4. After the third iteration, n = n * n = x4 * x4 = x8. And so on.

So you end up with n = n2^i on each iteration instead of ni.

1

u/RamenRin Oct 16 '18

Aaaaa i feel dumb lol🤦‍♂️ thanks so much I just changed it and ended up just having c=1 and then inside the loop i put c*=n which obvs solved the problem. Again thanks a lot! Honestly programming is fun but I always get confused with small things and make dumb mistakes (like writing lines of code in the wrong order) but I honestly enjoy it hahahah

1

u/icecapade Oct 16 '18

No problem! I'm no stranger to little mistakes, ha. Debugging can be one of the most fun things about programming, and also one of the most frustrating.

2

u/phonebatterylevelbot Oct 14 '18

this phone's battery is at 13% and needs charging!


I am a bot. I use OCR to detect battery levels. Sometimes I make mistakes. sorry. ^^info