// This program calculates a series of n values using iterative formula // x(1) = 0.3, x(2) = -0.3, ..., x(i) = i + sin(x(i-2)), i = 3, 4 ...n #include #include #include const int MAXSIZE = 100; // function prototype double diff(double x); int main() { // ---------------------------------begin solution for part (1) // declarations int n; Array x; x.setSize(MAXSIZE); // input value cout << "Enter your value n (n>=3) "; cin >> n; cout << endl; x(0) = 0.3; x(1) = -0.3; // main iteration to generate x(i) for (int i=2; i < n; i++) { x(i) = (i+1) + sin(x(i-2)); } // ----------------------------------end solution for part (1) // begin diagnostic output cout << "\t\t Begin DIAGNOSTIC\n"; for (int i=0; i < n; i++) { cout << "\t\tx(" << (i+1) << ") = " << x(i) << endl; } cout << "\t\t End DIAGNOSTIC\n"; // end diagnostic output // ----------------------------------begin solution to part (2) // find the nearest to its whole neighbour double mindiff = diff(x(0)); double mindiffx = x(0); for(int i = 1; i < n ; i++) { if (mindiff > diff(x(i))) { mindiff = diff(x(i)); mindiffx = x(i); } } // begin diagnostic output cout << "\t\t Begin DIAGNOSTIC\n"; for (int i=0; i < n; i++) { cout << "\t\tDiff(" << (i+1) << ") = " << diff(x(i)) << endl; } cout << "\t\t End DIAGNOSTIC\n"; // end diagnostic output cout << "The following number has smallest difference with its whole neighbour:\n" << mindiffx << endl; // begin diagnostic output cout << "\t\t Begin DIAGNOSTIC\n"; cout << "\t\tThe difference is: " << mindiff << endl; cout << "\t\t End DIAGNOSTIC\n"; // end diagnostic output } // end main() // function to calculate the abs value of the difference // between a double and its nearest whole rounding double diff(double x) { double difference; if (fabs(x-floor(x)) >= fabs(x-ceil(x))) { difference = fabs(x-ceil(x)); } else { difference = fabs(x-floor(x)); } return difference; } // end diff //---------------------------------- end of solution to part (2)