Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <locale.h>
- #include <math.h>
- #include <errno.h>
- #include <string.h>
- #include <stdlib.h>
- double factorial(int n);
- double next_series_member(double x, int i);
- double enter_double(double *result);
- int main()
- {
- setlocale(LC_ALL, "RUS"); //Подключение русского языка
- char *err_msg = "An error has occured";
- double step;
- int cnt, n, i, N = 0;
- double x, delta, sh = 0, precision = 0.000001;
- //Часть 1: вычисление N
- for (i = 0; i < 2;)
- {
- n = 0;
- sh = 0;
- printf("Enter x%d: ", i + 1);
- if (enter_double(&x) != 1) //Если возникла ошибка
- {
- printf("Please, enter correct value.\n");
- continue;
- }
- delta = fabs(sinh(x) - sh);
- while (delta > precision)
- {
- sh = sh + next_series_member(x, n);
- n++;
- delta = fabs(sinh(x) - sh);
- }
- if (errno == EDOM || errno == ERANGE) //Проверка на ошибки
- {
- perror(err_msg);
- printf("Please, enter correct value.\n");
- errno = 0;
- continue;
- }
- i++;
- if (n > N) N = n;
- }
- //Часть 2: вывод таблицы
- step = 0.1;
- cnt = 0;
- for (x = 0; x < 3.1; x += step) //От 0 до 3 с шагом 0,1
- {
- sh = 0;
- for (n = 0; n <= N; n++)
- {
- sh = sh + next_series_member(x, n);
- if (errno == EDOM || errno == ERANGE) //Проверка на ошибки
- {
- perror(err_msg);
- return -1;
- }
- }
- printf("%f ", sh);
- cnt++;
- if (cnt == 9) { //По 9 значений в строке
- printf("\n");
- cnt = 0;
- }
- }
- return 0;
- }
- double enter_double(double *result)
- /*Возвращает -1, если ошибка считывания, -2, если неверный формат ввода,
- выводит на экран сообщение об этих ошибках; в остальных случаях возвращает 1
- и записывает по адресу result введённое значение типа double*/
- {
- char str[1024];
- char *ptr;
- double value = 0;
- memset(str, '\0', 1024);
- if (gets(str) == NULL) //Считываем строку с клавиатуры
- {
- printf("An error has occured.\n");
- return -1; //Если не считалось
- }
- if (strlen(str) == 0) //Если введена пустая строка
- {
- printf("The string is empty.\n");
- return -2;
- }
- while ( (ptr = strchr(str, '.')) != NULL) //Замена всех точек на запятые
- {
- *ptr = ',';
- }
- errno = 0;
- ptr = NULL;
- value = strtod(str, &ptr); //Перевод в число с плавающей запятой
- if (errno != 0 || (ptr != NULL && *ptr != '\0')) //Если некорректный формат ввода
- {
- printf("Invalid input format.\n");
- return -2;
- }
- *result = value;
- return 1;
- }
- double factorial(int n) //Возвращает факториал числа n
- {
- if (n <= 1) return 1;
- else return n * factorial(n - 1);
- }
- double next_series_member(double x, int i) //Возвращает i-ый член ряда разложения sh(x)
- {
- return (pow(x, (2 * i + 1)) / factorial(2 * i + 1));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement