Is this the correct way to write the normal distribution function http://en.wikipedia.org/wiki/Normal_distribution or should I be using the pow function? I am really confused so help would be greatly appreciated :)
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdlib.h>
int main()
{
double u,s, N, x1,math1, math2, math3,n, v, x;
printf("Enter Mean: ");
scanf("%lf", &u);
printf("Enter Standard Deviation: ");
scanf("%lf", &s);
printf("Enter Number Of Inputs: ");
scanf("%lf", &N);
for (v=1; v<=N; v++)
{
printf("Enter Value: ");
scanf("%lf", &x);
n=(-1/2);
printf("f(x)= ");
math1 =1/(s*sqrt(2*M_PI));
math2= (x-u)/s * (x-u)/s;
math3= M_E * exp(n);
x1 = math1 * exp(math3)*exp(math2);
printf("%lf \n", x1);
}
system("Pause");
}
It's too hard to read your code, but I can tell it's wrong. Here is a short version:
double twopi = 8.0 * atan(1.0); // preferable to using M_PI
double x = ..., sigma = ..., mu = ...;
double y = (1.0 / (sigma * sqrt(twopi))) *
exp(-(x - mu)*(x - mu) / (2.0 * sigma * sigma));
Notice how I translate the mathematical formula directly to an expression in C... this makes it easy to verify that the code is correct. It's a bit harder when you use a bunch of temporary variables math1, math2, math3...
Remember: exp() is the same thing as its counterpart in mathematics, exp. So exp(x) is ex. Once you realize this, you will see the errors in your code.
Related
I have set the correct directory paths for Turbo C. But yet it gives the output as 0.000000
Following is the program:
#include <conio.h>
#include <math.h>
#include <stdio.h>
void main() {
int n;
float r, si, ci, p;
clrscr();
printf("enter principle amount\n");
scanf("%f", &p);
printf("enter rate of interest\n");
scanf("%d", &r);
printf("enter number of years\n");
scanf("%f", &n);
si = p * n * r / 100;
ci = p * (pow((1 + (r / 100)), n) - 1);
printf("simple interest=%f\n", si);
printf("compound interest=%f", ci);
getch();
}
It is supposed to give numbers instead of 0.000000
Any help?
Change:
scanf("%f",&n);
to:
scanf("%d",&n);
since n is an integer, not a float, as suggested in the comments already.
For r, which is of type float, you should use scanf("%f",&r);.
PS: Consider using a modern compiler, such as GCC.
This question already has answers here:
Reading in double values with scanf in c
(7 answers)
Closed 4 years ago.
I have a piece of code in C, which is supposed to compute the circumference.
No matter what I put in for variable Z when asked for it, it always prints 0.000000
Any ideas?
#include <stdio.h>
int main()
{
double pi = 3.1415926;
double z = 0.0;
printf("What is the radius of the circle? \n ");
scanf("%1f", &z);
double c = 2.0 * pi * z;
printf("The circumference is %1f", c);
return 0;
}
Change %1f to %lf.
Like so:
#include <stdio.h>
int main()
{
double pi = 3.1415926;
double z = 0.0;
printf("What is the radius of the circle? \n ");
scanf("%lf", &z);
double c = 2.0 * pi * z;
printf("The circumference is %lf", c);
return 0;
}
For reading into z, a double, you have to use scanf("%lf", &z) instead of "%1f".
You were very close. try this
#include <stdio.h>
int main()
{
double pi = 3.1415926;
double z = 0.0;
printf("What is the radius of the circle? \n ");
scanf("%1f", &z);
double c = 2.0 * pi * z;
printf("The circumference is %.1f", c);
return 0;
}
your logic is telling the float that it needs a whole number, but no decimals afterwards
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
But the calculation doesn't work or change when I run it and plug in any random number...need some guidance. I'm a novice to C and programming in general so please include easy to understand help.
#include <stdio.h>
double const change_celcius = 32.0;
double const change_kelvin = 273.15;
void temperatures(double n);
int main(void)
{
int q = 'q';
double user_number;
printf("Enter the fahrenheit: \n");
scanf("%f", &user_number);
while (user_number != q)
{
temperatures(user_number);
printf("\n");
printf("Enter the fahrenheit: \n");
scanf("%f", &user_number);
}
}
void temperatures(double n)
{
double celsius, kelvin;
celsius = 5.0 / 9.0 * (n - change_celcius);
kelvin = 5.0 / 9.0 * (n - change_celcius) + change_kelvin;
printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f",
n, celsius, kelvin);
}
I don't believe the all the use %lf instead of %f comments, by themselves, fix your program. The handling of q (for "quit") is also problematic so let's fix that too. First, we'll use POSIX function getline() to read it into a string and test if it's "q". If not, we'll sscanf it into a double and use it as our temperature:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
double const change_celsius = 32.0;
double const change_kelvin = 273.15;
void temperatures(double n)
{
double celsius = 5.0 / 9.0 * (n - change_celsius);
double kelvin = 5.0 / 9.0 * (n - change_celsius) + change_kelvin;
printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f\n", n, celsius, kelvin);
}
int main(void)
{
char *user_string = NULL;
ssize_t user_string_length;
size_t user_string_capacity = 0;
while (1)
{
printf("Enter the fahrenheit: ");
if ((user_string_length = getline(&user_string, &user_string_capacity, stdin)) < 1)
break;
if (strncmp(user_string, "q\n", (size_t) user_string_length) == 0)
break;
double user_number;
if (sscanf(user_string, "%lf", &user_number) == 1)
temperatures(user_number);
}
if (user_string != NULL)
free(user_string); // free memory allocated by getline()
if (user_string_length == -1)
putchar('\n'); // output courtesy newline if user used ^D to exit
return(0);
}
We check the return value of sscanf so that bad input won't cause the program to recalculate using the last good input. Instead, it will just prompt again for input.
You need to use "%lf" in scanf() and print() to read and write the value of type double.
Note that the printf() will work with "%f" too.
For more details please refer : Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?
There are several issues that can be addressed in your code. First, always (Always, in case it wasn't clear) check the return of scanf. That is the only way you know whether the expected number of conversions took place -- and whether you have an actual value to work with in your code.
The return also holds the key to exiting the loop when the user enters 'q' (or anything that causes the conversion to double to fail). By simply checking
if (scanf(" %lf", &user_number) == 1)
You can determine whether to process the value as a temperature, or tell the user has indicated exit.
Another tip, never (Never) write:
printf ("\n");
Why would you want to call a variadic function simply to output a single char? That is what putchar (or fputc) is for, e.g.:
putchar ('\n');
Putting those pieces together, and noting that %lf is used as the format specifier for double, you can rewrite your code, and format the output in quite a bit fewer lines, e.g.
#include <stdio.h>
double const change_celcius = 32.0;
double const change_kelvin = 273.15;
void temperatures (double n);
int main(void)
{
double user_number;
while (printf ("\nEnter temp in degrees fahrenheit: ") &&
scanf(" %lf", &user_number) == 1)
temperatures(user_number);
return 0; /* main() is type 'int' and returns a value to the shell */
}
void temperatures (double n)
{
double celsius, kelvin;
celsius = 5.0 / 9.0 * (n - change_celcius);
kelvin = 5.0 / 9.0 * (n - change_celcius) + change_kelvin;
printf(" fahrenheit: % 7.2lf\n celsius is: % 7.2lf\n kelvin is : % 7.2lf\n",
n, celsius, kelvin);
}
Example Use/Output
$ ./bin/temps
Enter temp in degrees fahrenheit: 212
fahrenheit: 212.00
celsius is: 100.00
kelvin is : 373.15
Enter temp in degrees fahrenheit: 0
fahrenheit: 0.00
celsius is: -17.78
kelvin is : 255.37
Enter temp in degrees fahrenheit: 68
fahrenheit: 68.00
celsius is: 20.00
kelvin is : 293.15
Enter temp in degrees fahrenheit: q
Always compile your code with at minimum -Wall -Wextra warnings enabled (and if you really want to drill down, add -pedantic). Read the warnings and fix them. All of your code should compile without warning before you consider your code reliable at this stage of the game.
Look all answers over, and let me know if you have any questions.
To read Double use %lf instead of %f.
for double printf() will work with %f also.
The calculation seems to be okay; however the you are not reading in the words properly
scanf("%f", &user_number);
You are stating you are reading in a float, yet you are declaring user_name as a double. If you wanted to use a float, you would need to change the user_name declaration from double to float. If you wanted to use a double use "%f".
I need to make a program in C that takes 3 coefficients, a, b, c, then solves for Delta. It then takes Delta and decides what Function to send it to determine it's output.
/*
*Program Name: COP 2220-10018 Project 4
*
* Author: Nathan Gamble
*
* Description: Find Delta, solve for roots.
*
* Input: Coefficients a, b, c.
*
* Output: Roots
*/
#include <stdio.h>
#include <math.h>
int main (void)
{
//Local Declarations
float a;
float b;
float c;
float delta;
//Statements
printf("Input coefficient a.\n");
scanf("%.2f", &a);
printf("Input coefficient b.\n");
scanf("%.2f", &b);
printf("Input coefficient c.\n");
scanf("%.2f", &c);
printf("%fx^2 + %fx + %f\n", &a, &b, &c);
//Process
delta = (b * b) - (4 * a * c);
if (delta > 0) twoRoots(a, b, c, delta);
else if (delta = 0) oneRoot(a, b, c, delta);
else if (delta < 0) noRoots();
return;
} // End main
/*
*Program Name: COP 2220-10018 Project 4
*
* Author: Nathan Gamble
*
* Description: To solve for the two roots.
*
* Input: None
*
* Output: Root one, Root two.
*/
#include <stdio.h>
#include <math.h>
int twoRoots ()
{
//Local Declarations
float xOne;
float xTwo;
float delta;
float deltaRoot;
float a;
float b;
printf("There are two distinct roots.\n");
deltaRoot = sqrt(delta);
xOne = (-b + deltaRoot) / (2*a);
xTwo = (-b - deltaRoot) / (2*a);
printf("%.2f", &xOne);
printf("%.2f", &xTwo);
return;
} // End twoRoots
/*
*Program Name: COP 2220-10018 Project 4
*
* Author: Nathan Gamble
*
* Description: To solve for the one root.
*
* Input: None
*
* Output: Root one.
*/
#include <stdio.h>
#include <math.h>
int oneRoot ()
{
//Local Declarations
float xOne;
float xTwo;
float deltaRoot;
float a;
float b;
printf("There is exactly one distinct root./n");
xOne = -b / (2*a);
printf("%.2f", &xOne);
return;
} // End oneRoot
/*
*Program Name: COP 2220-10018 Project 4
*
* Author: Nathan Gamble
*
* Description: To inform the roots are complex.
*
* Input: None
*
* Output: Statement.
*/
#include <stdio.h>
#include <math.h>
int noRoots ()
{
//Local Declarations
printf("There are two distinct complex roots./n");
return;
} // End noRoots
When I run it, I get the following Output:
Input coefficient a.
1
Input coefficient b.
Input coefficient c.
0.000000x^2 + 882156984598706310000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000.000000x + 0.000000
Process returned 16384 (0x4000) execution time : 10.641 s
Press any key to continue.
I only input 1, for a, and then it spits outt he remainder of the main method.
Few things that jump out first:
printf("Input coefficient a.\n");
scanf("%f", &a); // you were scanning for 0.2f .. any reason why?
printf("Input coefficient b.\n");
scanf("%f", &b);
printf("Input coefficient c.\n");
scanf("%f", &c);
your printf is also wrong .. change it to this:
printf("%0.2fx^2 + %0.2fx + %0.2f\n", a, b, c); // you were printing the addresses of a,b,c .. printf just needs the name of variables not their addresses
Output after doing above changes:
$ ./test
Input coefficient a.
1.5
Input coefficient b.
2.5
Input coefficient c.
3.5
1.50x^2 + 2.50x + 3.50
Fixed code: ( ask me if you have questions about any part )
#include <stdio.h>
#include <math.h>
// function declarations
void twoRoots (float a,float b,float delta);
void oneRoot (float a,float b,float delta);
int main (void)
{
//Local Declarations
float a;
float b;
float c;
float delta;
float solution;
printf("Input coefficient a.\n");
scanf("%f", &a);
printf("Input coefficient b.\n");
scanf("%f", &b);
printf("Input coefficient c.\n");
scanf("%f", &c);
printf("%0.2fx^2 + %0.2fx + %0.2f\n", a, b, c);
delta = (float)(b*b) - (float)(4.0 * a * c);
printf("delta = %0.2f\n",delta);
if (delta > 0){
twoRoots(a,b,delta);
}else if (delta == 0) {
oneRoot(a,b,delta);
}else if (delta < 0.0){
printf("There are no real roots\n");
}
return 0;
}
void twoRoots (float a,float b,float delta)
{
float xOne;
float xTwo;
float deltaRoot;
printf("There are two distinct roots.\n");
deltaRoot = sqrt(delta);
xOne = (-b + deltaRoot) / (2*a);
xTwo = (-b - deltaRoot) / (2*a);
printf("%.2f", xOne);
printf("%.2f", xTwo);
}
void oneRoot(float a,float b,float delta)
{
float xOne;
float xTwo;
float deltaRoot;
printf("There is exactly one distinct root\n");
xOne = -b / (2*a);
printf("%.2f", xOne);
}
Output1:
$ ./test
Input coefficient a.
1.1
Input coefficient b.
5.5
Input coefficient c.
2.2
1.10x^2 + 5.50x + 2.20
delta = 20.57
There are two distinct roots.
-0.44-4.56
Output2:
$ ./test
Input coefficient a.
1
Input coefficient b.
4
Input coefficient c.
4
1.00x^2 + 4.00x + 4.00
delta = 0.00
There is exactly one distinct root
-2.00
Output3:
$ ./test
Input coefficient a.
1
Input coefficient b.
3
Input coefficient c.
9
1.00x^2 + 3.00x + 9.00
delta = -27.00
There are no real roots
I optimised the code and made it a whole lot more efficient here :
http://pastebin.com/GS65PvH6
I think that the problem comes from the fact that 1 is recognized as an int and not a float.
When you write %.2f scanf expects you to input a float. If it detects something else it fails and does not read any other scanf requests as specified in the man page.
Your immediate problem lies here:
scanf ("%.2f", &a);
You can put a length limiter on the value to be scanned but you probably shouldn't be trying to limit what's input anyway.
In any case, the .2 option you're using is not valid for scanf, it's a printf thing controlling the precision of the output.
The ISO standard states that scanf needs "an optional decimal integer greater than zero that specifies the maximum field width (in characters)". So there's no way using just scanf to limit how many digits are allowed after the decimal point.
Use this instead:
scanf ("%f", &a);
including for the other scanf calls.
As to further problems, there are a few, some of which are below. I haven't provided an exhaustive list as the problem specific to your question is the scanf format string.
First, you want to print the values of those variables rather than their addresses:
printf ("%fx^2 + %fx + %f\n", a, b, c);
Second, you pass the variables a/b/c/delta to your functions but you do not receive them. You need to declare them something like:
int twoRoots (float a, float b, float c, float delta)
and ensure you remove any local variable declarations for those names so that they don't hide the passed-in ones (or cause compilation errors).
My Instructions: Write a program that starts out asking the user for the mean u and standard deviation s for the normal distribution (see the wiki article )
The program then asks for an N, and then asks for N values x. For each x it writes out f(x) to the screen. Note that the program asks the user for u, s, and N just once. After that it asks for N values for x, one by one. After each value x it writes out the corresponding value of the function.
What I am confused about is what the N is supposed to stand for. I assumed it was number of x's but can anyone clarify this for me?
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdlib.h>
int main()
{
double u,s, N, x1,math1, math2, math3,n, v, x;
printf("Enter Mean: ");
scanf("%lf", &u);
printf("Enter Standard Deviation: ");
scanf("%lf", &s);
printf("Enter number of x's: ");
scanf("%lf", &N);
for (v=1; v<=N; v++)
{
printf("Enter Value: ");
scanf("%lf", &x);
n=(-1/2);
printf("f(x)= ");
math1 =1/(u*sqrt(2*M_PI));
math2= (x-u)/s * (x-u)/s;
math3= M_E * exp(n);
x1 = math1 * exp(math3)*exp(math2);
printf("%lf \n", x1);
}
system("Pause");
}
N stands for number of inputs
pretty much clear from this part:
for (v=1; v<=N; v++)
If your instructions are as given, then N does indeed stand for the number of x values required.
Your program does just that, asking for N values of x.
First, it declares a variable N at the start of the program:
double u,s, N, x1,math1, math2, math3,n, v, x;
Then it prompts for input as an integer:
printf("Enter number of x's: ");
scanf("%lf", &N);
...and finally uses that integer to read in N values for x.
for (v=1; v<=N; v++)
{