Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <stdbool.h> // for bool
- // Check if the doubles are equal with 'eps' approximation
- bool sameDouble(double first, double second, double eps) {
- return fabs(first - second) < eps;
- }
- double f0(int value) {
- double x = (double)value + 12.28;
- double eps = 0.000001;
- // Check for bad parameter
- if (sameDouble(cos(x), 0.0000000000, eps)) {
- return -1;
- }
- return tan(x);
- }
- double f1(int value) {
- return (double)value - 7.92;
- }
- double f2(int value) {
- return sqrt(pow((double)value, 4) + 3.32);
- }
- int getUserInput(int *input, int INPUT_MIN, int INPUT_MAX) {
- int result = scanf_s("%d", input);
- if (result == 1 && *input >= INPUT_MIN && *input <= INPUT_MAX) {
- return 0;
- }
- return -1;
- }
- int main(int argc, char *argv[])
- {
- // Constants
- const int ROWS = 2;
- const int MIN_K = 1;
- const int MAX_INT = 1000000;
- const char* errorMessage = "ERROR - USER INPUT\n";
- const int ERROR = -1;
- int K;
- printf_s("K = ");
- if (getUserInput(&K, MIN_K, MAX_INT) == -1) {
- printf_s(errorMessage);
- return ERROR;
- }
- // Allocate memory and make each R[i, j]
- int **R;
- R = (int**)malloc(ROWS * sizeof *R);
- for(int row = 0; row < ROWS; ++row) {
- R[row] = (int*)malloc(K * sizeof *R[row]);
- for(int col = 0; col < K; ++col) {
- printf_s("R[%d][%d] = ", row, col);
- // Provided bad input
- if (scanf_s("%d", &R[row][col]) != 1) {
- printf_s(errorMessage);
- // Free memory (error occured on row-th itteration)
- for (int f = 0; f < row; ++f) {
- free(R[f]);
- }
- free(R);
- // Quit main with ERROR_CODE -1
- return ERROR;
- }
- }
- }
- // Allocate S array to store results
- double* S = (double*)malloc(sizeof(double) * K);
- // Create static array for functions pointers
- double (*functions[])(int) = { f0, f1, f2 };
- int value;
- int passValue;
- // Iterate over R to set elements of S
- for (int m = 0; m < K; ++m) {
- value = R[0][m];
- passValue = R[1][m];
- switch (value) {
- case 0:
- S[m] = functions[0](passValue);
- break;
- case 1:
- S[m] = functions[1](passValue);
- break;
- case 2:
- S[m] = functions[2](passValue);
- break;
- default:
- S[m] = R[1][m];
- break;
- }
- }
- // Print results to the user
- for (int i = 0; i < K; ++i) {
- printf_s("S[%d] = %f\n", i, S[i]);
- }
- // Free memory
- for(int i = 0; i < ROWS; ++i) {
- free(R[i]);
- }
- free(R);
- free(S);
- return 0;
- }
Add Comment
Please, Sign In to add comment