I wrote this code to find the roots of a quadratic equation.It seems to work unless I put a space before the scanning part. (for example in the input I write: a=1,b=2, c=1). In that case it just deletes the variable. (In the example I gave c would be deleted from the input and as such the answers I receive are 0,-2 instead of -1.). The code works if I put the space somewhere else (a =1,b= 2,c=1).
How can I fix this problem?
int main()
{
double root1 = 0, root2 = 0;
double a = 0., b = 0., c = 0.;
printf("Enter a polynomial:\n");
scanf("a=%lf,b=%lf,c=%lf", &a, &b, &c);
{
if (a == 0)
{
return 0;
}
if ((b * b - 4 * a * c) == 0)
{
root1 = -b / 2 * a;
printf("root is %f", root1);
}
else if ((b * b - 4 * a * c) < 0)
{
printf("There are no roots");
}
else {
root1 = (-b + sqrt(b * b - 4 * a * c)) / 2* a;
root2 = (-b - sqrt(b * b - 4 * a * c)) / 2* a;
printf("Roots are %f,%f", root1, root2);
}
}
return 0;
}
Use a format the allows for space in unexpected places. And check results.
// v v v v v v v v
if (scanf(" a =%lf , b =%lf , c =%lf", &a, &b, &c) == 3) Oh_Happy_day();
A space is not needed before "%lf" as that specifier will scan through leading white-space. Some like to be explicit
// x x x Optional
if (scanf(" a = %lf , b = %lf , c = %lf", &a, &b, &c) == 3) Oh_Happy_day();
Still better to use fgets() to read a line and then parse it.
there is no way to fix this problem; this is actually a problem with the function scanf(); itself. Alternately, you can use fgets(); instead.
try replacing
double a=0.,b=0.,c=0.;
printf("Enter a polynomial:\n");
scanf("a=%lf,b=%lf,c=%lf",&a,&b,&c);
with
double a=0.0,b=0.0,c=0.0;
printf("Enter a polynomial:\n");
scanf(" %lf, %lf, %lf",&a,&b,&c);
Because the space is not part of the formatting string you used in scanf.
You should add the leading space in the formatting string:
scanf(" a=%lf, b=%lf, c=%lf", &a, &b, &c);
Related
This is the code for finding the numerical solutions of 1D Heat Transfer Equation(well, possibly). The code is getting compiled but the console is not showing any output. The console is staying and not disappearing either. I have tried with getch() and getchar() also but the problem still persists. Please help!
Here's my code:
#include <stdio.h>
#include <math.h>
int
main (int argc, const char *argv[])
{
int a, p, tmax, tmin, l;
int i, j, n, o;
double m, T1, T2, x, al, H[l + 1][tmax + 1];
float k;
printf ("Enter the number of nodes: \n");
scanf ("%d", &a);
printf ("Enter the thickness of the wall: \n");
scanf ("%d", &l);
printf ("Enter the value of maximum time coordinate: \n");
scanf ("%d", &tmax);
printf ("Enter the value of minimum time coordinate: \n");
scanf ("%d", &tmin);
printf ("Enter the number of time steps: \n");
scanf ("%d", &p);
printf ("Enter the value of thermal diffusivity: \n");
scanf ("%f", &k);
printf ("Enter the value of initial temperature: \n");
scanf ("%lf", &T1);
printf ("Enter the values of temperature at both the boundaries: \n");
scanf ("%lf", &T2);
x = (l / (a - 1)); /*change in spacial coordinate*>
m = (tmax - tmin) / (p - 1); /*change in time coordinate*/
al = (k * (m)) / (pow (x, 2)); /*Formula for CFL constant*/
printf (" The vale of the constant is %lf\n", al);
printf ("the value of the constant should be less than 0.5 for the convergence of iterative
formula. \n");
for (o = 0; o <= tmax; o++)
{
H[0][o] = H[l][o] = T2; /*boundary condition*/
}
for (j = 1; j <= (l - 1); j++)
{
H[j][0] = T1; /*initial condition*/
}
if (al <= 0.5)
{
for (n = 0; n <= (tmax - 1); n++)
{
for (i = 1; i <= (l - 1); i++)
{
H[i][n + 1] =
H[i][n] + (al * (H[i + 1][n] - (2 * H[i][n]) + H[i - 1][n])); /* Iterative Formula for finding the temperature at each grid point*/
printf (" The value of Temperature[i,n] at [i,n] is:\n ");
printf ("%lf at %d , %d is", H[i][n], i, n);
printf ("\n");
}
}
}
else
{
printf ("Error! Solution is unstable. \n");
}
return 0;
}
What's wrong with my code?
Also, how can I take a mathematical function as input from the user instead of T2 in the place of the initial temperature? Sometimes, 1D unsteady heat transfer problems has initial temperature in the form of a mathematical function which can be algebric, trigonometric, hyperbolic etc. like in this problem
"Show that the solution of the ∂2θ/∂x2= ∂θ/∂t
satisfying the conditions (i) θ → 0 as t → ∞, (ii) θ = 0
when x = ±a for all values of t > 0, and (iii) θ = x when t = 0 and −a < x < a is
θ(x,t) = 2a/π ∑(n=1) to ∞((-1)^(n-1))(1/n)(sin(nπx/a) * (exp^((-((nπ)^2)* t)/a^2 )))"
So, I need to take a mathematical function as input from the user. Is there any way to do that using the C standard library? I found a way to do it using expression evaluator/parser but is there any other simpler way to solve this problem?
//Enter a 4-digit integer n from the keyboard, and write a program to divide it into two 2-digit integers a and B. Calculate and output the results of the addition, subtraction, multiplication, division and redundancy operations of the split two numbers. For example, n=-4321, if the two integers after splitting are a and b, then a=-43 and b=-21. The result of division operation requires that it be precise to 2 decimal places, and the data type is float. Redundancy and division operations need to take into account the division of 0, that is, if the split B = 0, then output the prompt information "The second operator is zero!"
//Failure to pass the test,how should i fix
#include<stdio.h>
#include<math.h>
int main()
{
int x, a, b;
printf("Please input n:\n");
scanf("%d", &x);
a = x / 100;
b = x % 100;
printf("%d,%d\n", a, b);
printf("sum=%d,sub=%d,multi=%d\n", a + b, a - b, a*b);
if (b == 0)
printf("The second operater is zero!");
else
printf("dev=%.2f,mod=%d\n", (float)a / b, a%b);
}
You forgot to check that x is a 4-digits number. So if the input is 12345 or 123 you don't satisfy the requirement.
#include <stdio.h>
int main()
{
int x, a, b;
int passed = 0;
// Enter a 4 digits number: ABCD
do {
printf("Enter X = ");
scanf("%d", &x);
passed = (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000);
} while (!passed);
a = x / 100;
b = x % 100;
printf("Numbers: %d %d \n", a, b);
printf("Sum = %d \n", a + b);
printf("Sub = %d \n", a - b);
printf("Mul = %d \n", a * b);
if (0 == b) {
printf("Div by Zero \n");
} else {
printf("Div = %f \n", (double)a / b);
printf("Mod = %d \n", a % b);
}
return 0;
}
#include <stdio.h>
#include <math.h>
#define M_PI 3.14
int main(void)
{
// Declaring Variables
float time, p1, p2, p3, voltage, p3_num, p3_dem, epsilon;
int index, type;
// Asking user for time and index values into equation
printf("Please enter a time value: ");
scanf("%f", &time);
printf("Please enter an index value: ");
scanf("%d", &index);
// Calculate value for given time, part a, b, or c
printf("Do you want to run type a, b, or c?: ");
scanf("%d", &type);
char again = 'Y';
while (again == 'Y')
{
if (type == 'a') {
int going = 'Y';
while (going == 'Y')
{
// Different parts of formula to ensure accuracy
printf("Please enter an index value: ");
scanf("%d", &index);
p1 = ((3 / 2) - 12 / pow((M_PI), 2));
p2 = (1 / pow((double)(2 * index - 1), 2));
p3_num = ((2 * index - 1) * M_PI * time);
p3_dem = 3;
p3 = cos(p3_num / p3_dem);
voltage = p1 * p2 * p3;
printf("time = %f", time);
printf("index = %i", index);
printf("voltage = %f", voltage);
printf("Again? (Y/N)");
scanf("%c", &going);
}
}
}
}
There is more underneath, but this is the main bulk. What I am confused about is that none of this running, none. I start at the very beginning and comment out everything else, not even my print statement is running. What is wrong?
You should divide your program up into smaller function so you can test them individually.
For example here would be a function that reads in one integer.
int GetInteger(const char * msg)
{
//read up on c style formatting here is a source http://en.cppreference.com/w/c/io/fscanf
int i = 0;
printf("%s", msg);
scanf("%i", &i);
printf("Program confirms: %i\n", i);
return i;
}
This will help you down the road. Read up on SOLID principles and Test Driven Development.
Here is a program that I'm trying to fix. I entered 1,5,6 and there should be 2 solutions and it said only 1 solution exists. I'm also trying to make it display decimal values(should I use double?). Below is my code, What am I doing wrong?
#include <stdio.h>
#include <math.h>
int main(void)
{
int inputs[3], a, b, c, d, x, x1, x2, i, lastDigit;
char *os, *noSol = "No solution\n", *cont = 'y';
while (cont == 'Y' || cont == 'y')
{
printf("This program solves a quadratic equation\n");
for (i = 1; i <= 3; i++)
{
lastDigit = i % 10;
if (i >= 4 && i <= 20)
os = "th";
if (i == 1 || lastDigit == 1)
os = "st";
else if (i == 2 || lastDigit == 2)
os = "nd";
else if (i == 3 || lastDigit == 3)
os = "rd";
else
os = "th";
printf("Enter your %d%s number: ", i, os);
scanf("%d", &inputs[i - 1]);
}
a = inputs[0];
b = inputs[1];
c = inputs[2];
while (1)
{
if (a == 0)
{
if (b == 0)
{
printf(noSol);
break;
}
else
{
x = -c / b;
printf("The equation is not quadratic and the solution is %d\n", x);
break;
}
}
else
{
d = pow(b, 2) - 4 * a * c;
if (d < 0)
{
printf(noSol);
break;
}
else if (d == 0)
{
x1 = -b / 2 * a;
printf("One solution: %d\n", x1);
break;
}
else if (d > 0)
{
x1 = (-b + sqrt(d)) / 2 * a;
x2 = (-b - sqrt(d)) / 2 * a;
printf("Two solutions: %d and %d\n", x1, x2);
break;
}
}
}
printf("Run program second time? ( Y / N )\n");
scanf("%s", &cont);
}
getch();
}
Many issues
The math part should use double (or float) instead of int.
double inputs[3], a, b, c, d, x, x1, x2;
printf() & scanf() for double, format specifier needs to change from %d to %le (or the like) to match double.
Math error: in 3 places, / 2 * a; should be / (2 * a);
char *cont = 'y' should be char cont[2] = "y"
scanf("%s", &cont); should be scanf("%1s", cont);.
Error handling: the return value of scanf() should be checked as in
if (1 != scanf("%lf", &inputs[i - 1])) { ; /* Handle error */ }
Minor math: if (d == 0) case results in a "double root", not a single solution. Practically speaking, given floating point math rounding, one does not always know d should have been mathematically exactly zero and thus the "single" root is really 2 very close roots. Further, with select values, the "Two solutions" will have the same value should sqrt(d) be much much smaller than b.
#include <stdio.h>
int main()
{
printf("choose number");
c();
}
c()
{
printf("1. ax+b=0\n\n");
printf("2. ax+by+c=0\n dx+ey+f=0\n\n");
int n;
scanf("%d", &n);
if (n > 3)
wrong();
if (n == 1)
formula1();
if (n == 2)
formula2();
if (n == 3)
;
formula3();
}
wrong()
{
printf("Please choose a number between 1 and 3.\n\n");
c();
}
formula1()
{
printf("ax+b=0\n");
printf("Enter your values for a and b respectively, seperated by commas\n");
float a, b, x;
scanf("%f,%f,%f", &a, &b);
x = -b / a;
printf("x=-b/a\n");
printf("=>x=%f", x);
question();
}
formula2()
{
printf("ax+by+c=0\n\ndx+ey+f=0\n");
printf(
"Enter your values for a, b, c, d ,e and f respectively, seperated by commas\n");
float a, b, c, d, e, f, x, y;
scanf("%f,%f,%f,%f,%f,%f", &a, &b, &c, &d, &e, &f);
x = ((f * b) - (c * e)) / ((a * e) - (d * b));
y = ((c * d) - (f * a)) / ((e * a) - (d * b));
printf("=>x=%f", x);
printf("\n\n");
printf("=>y=%f", y);
question();
}
question()
{
char t;
printf("\n\nanother equation?\ny/n?\n");
if (t == 'y')
{
printf("\n\n\n\n\n");
c();
}
else if (t != 'n')
question();
}
I have this code, which in short solves 3 equations.
When you select any choice it seems to run the question method multiple times then quits due to a segmentation fault: 11
Could someone please point out where I am going wrong. Any other help with my code would be greatly appreciated
Here is one problem:
scanf("%f,%f,%f",&a, &b);
Only two arguments are supplied for the three values.
There is no input function like scanf() in question() and so if t is not 'y' or 'n' by chance, you get an endless recursion until stack size is exceeded ...