My program to find the roots of a function using the quadratic formula is below. It works perfectly. However I was unable to get it to work without defining three of the variables globally; which, according to my project description, I am not supposed to do.
Any suggestions or alterations on how to define them locally and have the calculations not get lost before the print results function is able to do so?
#include <stdio.h>
#include <math.h>
double discriminant;
double root_one = 0, root_two = 0;
double a = 0, b = 0, c = 0;
int checkComplex(double a, double b, double c)
{
discriminant = (b * b) - 4 * (a * c);
if (discriminant == 0)
return 2;
else if (discriminant > 0)
return 1;
else
return 0;
}// end checkComplex
void calculateRoots(double a, double b, double c)
{
root_one = (-b + sqrt(discriminant)) / (2 * a);
root_two = (-b - sqrt(discriminant)) / (2 * a);
} // end calculateRoots
void getData()
{
printf("Enter a: ");
scanf("%lf", &a);
printf("\nEnter b: ");
scanf("%lf", &b);
printf("\nEnter c: ");
scanf("%lf", &c);
}// end getData
void printResults()
{
if (checkComplex(a, b, c) == 1)
{
calculateRoots(a, b, c);
printf("\n\n-----------------------------------------\n");
printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
root_two);
}// if discriminant is 1
else if (checkComplex(a, b, c) == 0)
{
printf("\n\n-----------------------------------------\n");
printf("The discriminant (b^2-4ac) is negative (imaginary)");
printf("\nTherefore, the roots are complex\n");
} // if discriminant is 0
else if (checkComplex(a == 2, b == 2, c == 2))
{
calculateRoots(a, b, c);
printf("\n\n-----------------------------------------\n");
printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
root_two);
}// if discriminant is greater than 1
} // end printResults
int main()
{
getData();
printResults();
return 0;
} // End program
If you need to return multiple values, you can return a struct, or you can accept pointers to where the result should be stored. I've used both approaches in the following solution:
#include <stdio.h>
#include <math.h>
typedef struct {
double discriminant;
char num_roots;
double roots[2];
} roots_t;
void getData(double* ap, double* bp, double* cp) {
printf("Enter a: "); scanf("%lf", ap);
printf("Enter b: "); scanf("%lf", bp);
printf("Enter c: "); scanf("%lf", cp);
}
roots_t calculateRoots(double a, double b, double c) {
roots_t roots;
roots.discriminant = (b*b) - 4 * (a*c);
roots.num_roots = 0;
if (roots.discriminant >= 0) {
roots.roots[roots.num_roots++] = (-b + sqrt(roots.discriminant)) / (2 * a);
if (roots.discriminant > 0)
roots.roots[roots.num_roots++] = (-b - sqrt(roots.discriminant)) / (2 * a);
}
}
return roots;
}
void printResults(double a, double b, double c, roots_t roots) {
if (roots.num_roots == 2) {
printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
printf("roots = %.2lf, %.2lf\n", roots.roots[0], roots.roots[1]);
}
else if (roots.num_roots == 1) {
printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
printf("roots = %.2lf\n", roots.roots[0]);
}
else {
printf("The discriminant (b^2-4ac) is negative\n");
printf("roots = <complex>\n");
}
}
int main(void) {
double a, b, c;
getData(&a, &b, &c);
printResults(a, b, c, calculateRoots(a, b, c));
return 0;
}
Related
This is my code the only thing I can do is quit. There are two functions one where it calculates Fahrenheit to Celsius and the other does the opposite and there is an array that stores the data as well. Then I added the switch at the end. I understand each concept individually but don't know how to bring them together.
#include <stdlib.h>
#define SIZE 1
//C = (5 / 9) * (F - 32) and F = (9 / 5) * C + 32
// calculate f to c
int getValue() {
int result;
printf("Input degree: ");
scanf_s("%i", &result);
return result;
}
int F (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (9 / 5) * input[a] + 32;
}
return result;
}
int C (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (5 / 9) * (input[a] - 32);
}
return result;
}
main() {
int choice;
int input[SIZE];
int F, C;
int a;
for (a = 0; a < SIZE; a++) {
input[a] = getValue();
F = (input, SIZE);
C = (input, SIZE);
}
do {
printf("Welcome to the Main Menu\n");
printf("1. Convert temperature input from the user in degrees Fahrenheit to degrees Celsius\n");
printf("2. Convert temperature input from the user in degrees Celsius to degrees Fahrenheit\n");
printf("3. Quit.\n");
scanf_s("%i", &choice);
} while (choice != 3);
switch (choice) {
case 1:
printf("%i degree C\n", F);
break;
case 2:
printf(" % i degree F\n", C);
break;
case 3:
printf("You have chosen option 3 you are now able to quit\n");
break;
}
system("pause");
}```
Beside the errors pointed in the answer by #Mehmet Aslan, you should move the switch block into the while loop, so it gets executed each time the user selects an option. As it is now, it will only be run once, when the user has chosen the option "3"
Since this looks like homework here is constructive feedbacks. Hopefully you ll manage.
Hints:
Look into pointers
int getValue();
void F(int *output, int *input, int size);
void C(int *output, int *input, int size)
{
for(int i = 0; i < size; ++i)
{
output[i] = (5 / 9) * (input[i]- 32);
}
}
#include <stdlib.h>
#define SIZE 1
//C = (5 / 9) * (F - 32) and F = (9 / 5) * C + 32
// calculate f to c
int getValue() {
int result;
printf("Input degree: ");
scanf_s("%i", &result);
return result;
}
int F (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (9 / 5) * input[a] + 32;
}
return result;
}
int C (int input[], int size) {
int result = 0;
int a;
for (a = 0; a = size; a++) {
if (input[a] = result);
result = (5 / 9) * (input[a] - 32);
}
return result;
}
main() {
int choice;
int input[SIZE];
int F, C;
int a;
for (a = 0; a < SIZE; a++) {
input[a] = getValue();
F = (input, SIZE); <<---compile time error, not a function call
C = (input, SIZE); <<---compile time error, not a function call
}
// F(output, input, SIZE) <<--- it should be here, so you could calculate after collect inputs
do {
printf("Welcome to the Main Menu\n");
printf("1. Convert temperature input from the user in degrees Fahrenheit to degrees Celsius\n");
printf("2. Convert temperature input from the user in degrees Celsius to degrees Fahrenheit\n");
printf("3. Quit.\n");
scanf_s("%i", &choice);
} while (choice != 3);
switch (choice) {
case 1:
printf("%i degree C\n", F); <<---F compile time error, not a function call
break;
case 2:
printf(" % i degree F\n", C); <<---C compile time error, not a function call
break;
case 3:
printf("You have chosen option 3 you are now able to quit\n");
break;
}
system("pause");
}
How do i proplerly clear input buffer since fflush(stdin) is undefined and only available in some compilers,
My plan is to clear input since after looping back it still use the buffered input rather than getting a new input.
Here is my code:
#include <stdio.h>
#include <stdbool.h>
//bool function
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
int main()
{
//local variable
double result, a, b;
char oper, option = 'y';
//loop
while(option == 'y')
{
system("cls");
printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
scanf("%lf %c %lf", &a, &oper, &b);
// nested if
if(isInteger(a) && isInteger(b))
{
if(oper == '+')
{
result = a + b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else if(oper == '-')
{
result = a - b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else if(oper == '*')
{
result = a * b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else if(oper == '/')
{
result = a / b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else
{
//output error
printf("Invalid Operater!\n");
}
}
else
{
//output error
printf("Input is not a digit!\n");
}
//output selection
printf("Do you want to retry y/n?");
option = getch();
} // end loop
}
I only use scanf since we are still in scanf and printf.
Please help me out, this is our first project in college.
I have tried this program to take 3 integers and print the 2nd largest number:
#include<stdio.h>
int main()
{
int a,b,c,max2;
printf("Enter 3 integers: ");
scanf("%d%d%d",&a,&b,&c);
max2=a;
if(a>b){
max2=b;
printf("")
}
return 0;
}
Now i am stuck here. I am unable to find the logic behind this code. What can I do?
This is not the Logic which you can understand, it'll not give you the right, expected result.
Code:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Values: ");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
if(b>c)
printf("2nd largest: %d", b);
else
printf("2nd largest: %d", c);
}
else if(b>c && b>a)
{
if(c>a)
printf("2nd largest: %d", c);
else
printf("2nd largest: %d", a);
}
else if(a>b)
printf("2nd largest: %d", a);
else
printf("2nd largest: %d", b);
return 0;
}
You should compare all the three variables to get the 2nd largest among those numbers.
Output:
Values: 32 31 12
2nd largest: 31
Explanation:
First pick any variable and compare it with the other two variables like if(a>b && a>c), if its true, it means a is the largest and any of the two variables b and c is the 2nd largest, so inside the if(a>b && a>c) block there's a comparison if(b>c), if true then b is the 2nd largest otherwise c is the second largest. Similarly, compare the other two variables for if they are the largest. e.g. else if(b>c && b>a) and else if(c>a && c>b).
One method is to sort these three numbers and then print the middle one:
#include <stdio.h>
static inline void swap_if_out_of_order (int *p, int *q)
{
if (*p > *q) {
int t = *p;
*p = *q;
*q = t;
}
}
int main (void)
{
int a, b, c;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3) {
swap_if_out_of_order(&a, &b);
swap_if_out_of_order(&b, &c);
swap_if_out_of_order(&a, &b);
printf("Second greatest: %d\n", b);
}
}
Or, without sorting, with at most three comparisons:
#include <stdio.h>
int main (void)
{
int a, b, c, m;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3) {
if (a > b) {
if (b > c) m = b;
else if (a > c) m = c;
else m = a;
} else if (a > c) m = a;
else if (b > c) m = c;
else m = b;
printf("Second greatest: %d\n", m);
}
}
or, likely the most efficient way with max and min functions:
#include <stdio.h>
static inline int min (int x, int y) { return x < y ? x : y; }
static inline int max (int x, int y) { return x > y ? x : y; }
int main (void)
{
int a, b, c;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3)
printf("Second greatest: %d\n", max(min(a, b), min(max(a, b), c)));
}
JS recursion:
function f(a,b,c) {
if(a>=b && c<b) return b;
if(a>b) return f(a,c,b);
return f(b,a,c);
}
f(2,12,0) // 2
#include <stdio.h>
main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
// largest //
if(a>b&&a>c)
printf("largest=%d",a);
if(b>a&&b>c)
printf("largest=%d",b);
if(c>b&&c>a)
printf("largest=%d",c);
// second largest//
if(a>b&&a<c)
printf("\nscenond largest=%d",a);
if(b>a&&b<c)
printf("\nscenond largest=%d",b);
if(c>a&&c<b)
printf("\nscenond largest=%d",c);
}
this will output the largest and the second largest number.
#include <stdio.h>
int main()
{
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b)
{
temp = a;
a = b;
b = temp;
}
else if (b > c)
{
temp = b;
b = c;
c = temp;
}
else if (c > a)
{
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
If I put 8,6,3, the output comes 6,8,3. It doesn't change the last number. I am trying to arrange three 3 numbers in ascending manner using if statement, but this doesn't work for the third number. What can be done about it?
It easiest if you first find the smallest, then make sure the remaining two are correct :
int main()
{
int a, b, c, temp;
int ret = scanf("%d %d %d", &a, &b, &c);
if (ret != 3) {
printf("scanf() error\n");
exit(1);
}
// get smallest into a
if ((b < a) && (b < c)) {
temp = a;
a = b;
b = temp;
} else if ((c < a) && (c < b)) {
temp = a;
a = c;
c = temp;
}
// a is smallest, check b and c
if (c < b) {
temp = b;
b = c;
c = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
You need to use if instead of else if as you want to compare a with b, b with c and a with c (the three and not only one of them). Moreover, as you are moving the numbers you have to take into account where they are moved for the last comparison. And your third condition was wrong. So this should be what you are trying to do:
#include <stdio.h>
int main(){
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b){
temp = a;
a = b;
b = temp;
}
if (b > c){
temp = b;
b = c;
c = temp;
if (a > b){
temp = a;
a = b;
b = temp;
}
}
else if (a > c){
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
I think you have misunderstood the concept of if else if structure, In your case it is not working for third number because the execution will reach to else if part only when the if condition is false.
#include <stdio.h>
int main()
{
int a,b,c,temp;
scanf("%d %d %d",&a,&b,&c);
if(a>b) //evaluates to true.
{
temp=a;
a=b;
b=temp;
}
else if(b>c) // not able to execute.
{
temp=b;
b=c;
c=temp;
}
else if(c>a) // not able to execute
{
temp=c;
c=a;
a=temp;
}
printf("%d %d %d",a,b,c);
return 0;
}
a = 8
b = 6
c = 3
checking a>b evaluates to true hence swapped
now:
a = 6 // your output
b = 8
c = 3
you may need to go over the concept of if else structure once again
#include<stdio.h>
int main()
{
int a ,b,c;
printf("Enter the number : \n");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
{
if(b>c)
printf("%d %d %d",a,b,c);
else
printf("%d %d %d",a ,c,b);
}
else if((b>c)&&(b>a))
{
if(c>a)
printf("%d %d %d",b,c,a);
else
printf("%d %d %d",b,a,c);
}
else if((c>a)&&(c>b))
{
if(a>b)
printf("%d %d %d",c,a,b);
else
printf("%d %d %d",c,b,a);
}
return 0;
}
The easiest way is to use an array instead of three individual variables. Then use qsort for getting the input sorted.
Like:
#include <stdio.h>
#include <stdlib.h>
// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
if (*(int*)p1 < *(int*)p2) return -1;
if (*(int*)p2 < *(int*)p1) return 1;
return 0;
}
int main()
{
int arr[3];
if (scanf("%d %d %d", &arr[0], &arr[1], &arr[2]) != 3) exit(1);
// Sort the input
qsort(arr, sizeof(arr)/sizeof(int), sizeof(int), cmp);
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
return 0;
}
#include <stdio.h>
int main()
{
int a,b,c,temp,min;
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(c<a)
{
min=c;
c=b;
b=a;
a=min;
}
else if(c>a && b<c) {
min=c;
c=b;
b=min;
}
printf("%d %d %d",a,b,c);
return 0;
}
you are comparing using else if, if any one condition satisfies it won't execute the other else condition.
I in my program, I'm attempting to create two different variables that will look the user's input integers and count how many are over 20 and how many are between 10 and 90. Unfortunately, both functions (counter_20 and between_count) return the same result, and when printed, it is an exorbitantly high and incorrect number. Any help would be greatly appreciated! My code is as follows:
#include <stdio.h>
#include <stdbool.h>
int getNumber(void);
float average_counter(int sum, int numCounter);
int counter_20(int input);
int between_counter(int input);
void print_results(int sum, int average, int numCounter, int sumOfTwenties, int betweenCount);
int main (void){
int a, b, c, e, f;
float d;
bool x = true;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
while(x = true){
if(a != 9999){
if(a != 0){
b += a;
c++;
d = average_counter(b, c);
e = counter_20(a);
f = between_counter(a);
}
else{
printf("No input was provided.");
}
}
else{
break;
}
}
print_results(b, d, c, e, f);
}
int getNumber(void){
int input;
printf("Please input an integer. If you would like to stop inputting integers and see the$
scanf(" %d", &input);
return input;
}
float average_counter(int sum, int numCounter){
float average;
average = sum/numCounter;
return average;
}
//One of my functions for counting the number of integers over 20
int counter_20(int input){
int countTwenties;
if(input > 20){
++countTwenties;
}
printf(" %d", countTwenties);
return countTwenties;
}
//my function for counting the integers between 10 1nd 90
int between_counter(int input){
int betweenCount;
if(input < 90){
if(input > 10){
++betweenCount;
}
else{
}
}
return betweenCount;
}
void print_results(int sum, int average, int numCounter, int countTwenties, int betweenCount){
printf("\nThe sum is: %d", sum);
printf("\nThe average is: %d", average);
printf("\nThe number of integers is: %d", numCounter);
printf("\nThe number of integers over 20 is: %d", countTwenties);
printf("\nThe number of integers between 10 and 90 is: %d", betweenCount);
return;
}
int counter_20(int input){
int countTwenties;
if(input > 20){
++countTwenties;
}
printf(" %d", countTwenties);
return countTwenties;
}
countTwenties is uninitialized and using uninitialized variables lead to undefined behavior. Fix it by initializing the variable like
int countTwenties=0;
As pointed out in my comment
while(x = true)
should be
while(x == true)
Normally compiler throws a warning when you have something like this in the code