IZP/Cviko2_1/main.c
2024-09-26 22:20:05 +02:00

105 lines
2.4 KiB
C

#include "types.h"
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
void read_print_quadratic() {
// TODO 1. Read 3 numbers: a, b and c which represent known numbers for
// quadratic equation in standard format (ax^2 + bx + c = 0) from stdin.
printf("Enter numbers a, b and c of equation ax^2 +bx + c = 0:\n");
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
// TODO 2. Check if equation is quadratic. If so, calculate its discriminant
// and, if possible, print all roots to stdout.
if (a == 0 || (a == 0 && b == 0 && c == 0)) {
printf("Please enter a cooler formula");
return;
}
double d = b * b + (-4) * a * c;
printf("Discriminant: %.2f\n", d);
if (d < 0) {
printf("Discriminant is lower than 0, cannot solve equation in R");
return;
}
double rootA, rootB;
rootA = (-b + sqrt(d)) / (2*a);
rootB = (-b - sqrt(d)) / (2*a);
if (rootA == rootB) {
printf("Equation has one solution: %.2f", rootA);
} else {
printf("Equation has two solution: %.2f and %.2f", rootA, rootB);
}
return;
}
void read_print_is_character() {
// TODO 1. Read one character from stdin.
printf("Enter a character:\n");
char l;
scanf(" %c", &l);
// TODO 2. Determine whether the character represents a letter (a-z, A-Z) or
// not and print the result to stdout.
if ((l >= 'a' && l <= 'z') || (l >= 'A' && l <= 'Z')) {
printf("%c IS a letter (a-z or A-Z)", l);
} else {
printf("%c is NOT a letter (a-z or A-Z)", l);
}
return;
}
void read_print_factorial() {
printf("Enter a number for calcuation of factorial:\n");
// TODO 1. Read one number from stdin.
int a;
scanf("%d", &a);
// TODO 2. Print its factorial (!) to stdout.
for (int i = a - 1; i != 0; --i) {
a *= i;
}
printf("Factorial: %d", a);
return;
}
void read_print_gcd() {
// TODO 1. Read two numbers from stdin.
printf("Enter two numbers to calculate gcd:\n");
int a, b;
scanf("%d %d", &a, &b);
// see https://en.wikipedia.org/wiki/Greatest_common_divisor#Euclidean_algorithm
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
printf("gcd is %d\n", a);
return;
}
#ifndef TEST_BUILD
int main() {
printf("\n--read_print_quadratic--\n");
read_print_quadratic();
printf("\n--read_print_is_character--\n");
read_print_is_character();
printf("\n--read_print_factorial--\n");
read_print_factorial();
printf("\n--read_print_gcd--\n");
read_print_gcd();
return 0;
}
#endif