# reassigning a variable with a divide operator gives nan in program when zero is entered [closed]

Please keep in mind that I am very new to programming.

I was given a the following question as my assignment in C++:

Write a program that computes the value of an nth degree polynomial $$A(x)=a_0+a_1x+a_2x^2+....a_nx^n.$$ Assume that you are given n, and then the value of x, and then the coefficients in the order of increasing subscripts.

This was fairly manageable and I had created a program which did just that. But I encountered a problem. In my program, I had used repeat statements which are as shown below:

"simplecpp" is a downloaded library developed by IIT Bombay to help in teaching new programmers, which I have installed

#include<simplecpp>

main_program{
int n; float x, a, t, S;
cout<<"Program for finding the value of a0 + a1x +a2x^2 + ...... + anx^n"<<endl;
cout<<"Enter the value of n:";
cin>>n;
cout<<"Enter the value of x:";
cin>>x;
cout<<"Enter the values of coefficients a0, a1,... in order:";
cin>>a;
t=a;
S=a;
repeat(n){
t=t/a;
cin>>a;
t=t*a*x;
S=S+t;
}
cout<<"The value of the polynomial="<<S;
}


It was fine until one of the coefficients became zero, and it is understandable, because of the t=t/a statement.

Please note that I am a beginner and have not yet completed the major parts, like arrays, if and loops. So, the repeat statement is basically my major tool.

Is it possible to write a program with just my knowledge for even zero coefficients?

• Perhaps this question is best suited on Stack Overflow Commented Jul 2 at 13:57

The pattern of multiplying t by a, then dividing by a to recover the original value is not a good one. You do not need to store that value in t to add it to S, and could make t be $$\x^i\$$ instead of $$\a_i x^i\$$. Using somewhat more descriptive variable names, the business part of your code could look like:

cin >> a;
powers_of_x = 1;
total_sum = a;
repeat(n) {
cin >> a;
powers_of_x *= x;
total_sum += a * powers_of_x;
}


and avoid the issue altogether.

Note though that the "correct" way of evaluating a polynomial minimizing operations is to iterate over the coefficients in reverse order, using what's known as Horner's Scheme.