#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct Node
{
int coef;
struct Node *ptr;
} node;
void createLinkList(node **head, int degree){
node *temp, *last, *tempHead;
tempHead = (node *)malloc(sizeof(node));
tempHead->ptr = NULL;
scanf("%d", &(tempHead->coef));
last = tempHead;
for (int i = 1; i < degree + 1; i++){
temp = (node *)malloc(sizeof(node));
scanf("%d", &(temp->coef));
temp->ptr = NULL;
last->ptr = temp;
last = temp;}
*head = tempHead;}
int findVal(node *head, int degree, int x){
int result = 0;
while (head != NULL){
result += (head->coef) * pow(x, degree);
head = head->ptr;
degree--;}
return result;}
int main()
{
node *head;
int power;
int x;
scanf("%d",&power);
createLinkList(&head,power);
scanf("%d",&x);
int k = findVal(head,power,x);
printf("k = %d",k);
// int n = 4*pow(5,2);
// printf("n = %d",n);
}
So here is a simple C language code. The createLinkList()
function is for creating a linked list and findVal()
is for evaluating a polynomial.
For other values of x, my code is running fine but, whenever I take x=5, the code gives wrong output.
For example if I take: n = 2, coef = 4, 0, 5 and x = 5 (which is equivalent to giving input in one line as follows: 2 4 0 5 5), then obviously the output (value of k) should be 105 (4*(x^2) + 0*(x^1) + 5).
But in my terminal output is showing 104. You can check this code in your IDE. As much as I know, there is no problem in createLinkList() function.
Could anyone please tell why this is happening?