I faced with a problem when solving a task from university.
The task is to do the algorithm of calculating and the program on C for determinating function's value, which is:
F = (E_1 - E_2 + E_3) / (E_1 * E_3)
where
E_1 = sin(x + 3), E_2 = tg(a), E_3 = a^x + b
whereas x, a, b - the users input.
The problem is in namely output! The numbers of there very big and inappropriate! The code below:
int main()
{
int x, a, b;
printf("Put the x value: ");
x = scanf("%i", &x); //x = 1
printf("Put the a value: ");
a = scanf("%i", &a); //a = 1
printf("Put the b value: ");
b = scanf("%i", &b); //b = 1
double E_1 = sin(x + 3);
double E_2 = tan(a);
double E_3 = pow(a, x) + b;
double F = (E_1 - E_2 + E_3) / (E_1 * E_3);
printf("Then, the F = %i", &F);
return 0;
}
And, for example, if x, a, b = 1, the output is 5502604, which is false!
There are at least a couple of problems in the posted code.
int x;
printf("Put the x value: ");
x = scanf("%i", &x); //x = 1
scanf returns the number of times a value is correctly assigned to one of its argument pointers or EOF if end-of-file (or an input error) occurs before any values are stored. So, this line and the others will always assign 1 (or 0, or EOF, which is usually -1, if an error occurs) to the variables, whatever values the user entered.
It's unclear why the variables x, a and b are declared as ints rather than doubles.
double F = /* ... */;
printf("Then, the F = %i", &F);
// ^^ ^^
Here the wrong format (%i is used for integers, a double requires %f or %lf) specifier it's used and the wrong value is passed (the address of F instead of F).
Related
I have problems for my function, since after the first expression, the values inserted to my parameters (float x, float y) suddenly becomes 0.
I called this function with main (), the output for c = x/y works as expected. But for d = x - (y * c), it gives me an output of 0, I check where the problem is and it appears to be because of x and y since they both have 0 values for some reason
I have not finished my function for greatest common divisor, since I'm still stuck at this problem
'''
int gcd (float x, float y)
{
int c = x / y;
printf ("This's your quotient: %d\n", c);
int d = x - ( y * c ); // d = 0 since y, x = 0
printf ("This's your remainder: %d\n", d);
printf ("c %d\n",c); // works normally
printf ("y %f\n",y); // y = 0
printf ("x: %f\n",x); // x = 0
}
Here is example code that fixes the issues I noticed and changing the signature to separate calculations from output:
#include <stdio.h>
void quotient_reminder(unsigned x, unsigned y, unsigned *q, unsigned *r) {
if(y == 0) return;
*q = x / y;
*r = x - (y * *q); // d = 0 since y, x = 0
}
int main() {
unsigned q, r;
quotient_reminder(25.0, 7.1, &q, &r);
printf ("This's your quotient: %u\n", q);
printf ("This's your remainder: %u\n", r);
}
and it will return:
This's your quotient: 3
This's your remainder: 4
-use double precision
-use sqrt() and exponential function exp()
-use * to compute the square
-do not use pow()
I am getting values they are just not anything as to what I expected. I tried making them all signed but it didn't change anything and I've tried printing out with 12 decimal places and nothing seems to be working.I have linked the math library and defined it as well.
double normal(double x, double sigma, double mu)
{
double func = 1.0/(sigma * sqrt(2.0*M_PI));
double raise = 1.0/2.0*((x-mu)/sigma);
double func1 = func * exp(raise);
double comp_func = (func1 * func1);
return comp_func;
}
int main(void)
{
// create two constant variables for μ and σ
const double sigma, mu;
//create a variable for x - only dynamic variable in equation
unsigned int x;
//create a variable for N values of x to use for loop
int no_x;
//scaniing value into mu
printf("Enter mean u: ");
scanf("%lf", &mu);
//scanning value into sigma
printf("Enter standard deviation: ");
scanf("%lf", &sigma);
//if sigma = 0 then exit
if(sigma == 0)
{
printf("error you entered: 0");
exit(0);
}
//storing number of x values in no_x
printf("Number of x values: ");
scanf("%d", &no_x);
//the for loop where i am calling function normal N times
for(int i = 1; i <= no_x; i++)
{
//printing i for the counter in prompted x values
printf("x value %d : ", i);
// scanning in x
scanf("%lf", &x);
x = normal(x,sigma,mu);
printf("f(x) = : %lf.12", x);
printf("\n");
}
return 0;
}
C:>.\a.exe
Enter mean u: 3.489
Enter std dev s: 1.203
Number of x values: 3
x value 1: 3.4
f(X) = 0.330716549275
x value 2: -3.4
f(X) = 0.000000025104
x value 3: 4
f(X) = 0.303015189801
But this is what I am receiving
C:\Csource>a.exe
Enter mean u: 3.489
Enter standard deviation: 1.203
Number of x values: 3
x value 1 : 3.4
f(x) = : 15086080.000000
x value 2 : -3.4
f(x) = : 15086080.000000
x value 3 : 4
f(x) = : 1610612736.000000
Insert these lines:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Change:
const double sigma, mu;
to:
double sigma, mu;
Change:
unsigned int x;
to:
double x;
Replace the definition of the normal function with:
double normal(double x, double sigma, double mu)
{
double func = 1.0/(sigma * sqrt(2.0*M_PI));
double t = (x-mu)/sigma;
return func * exp(-t*t/2);
}
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#include<math.h>
#include<stdio.h>
#include <stdlib.h>
double normal(double x, double sigma, double mu)
{
double func = 1.0/(sigma * sqrt(2.0*M_PI));
double t = (x-mu)/sigma;
return func * exp((-0.5*t)* t);
}
I Finally got this code above working after tweaking with it literally all day lol, C math can be rather tricky, thank you for the help above as well.
I am writing a basic program to calculate an arithmetic-geometric mean using command line arguments using C. However the program doesn't seem to be recognizing anything I type in. Here is my code:
/*
*This program will calculate an arithmetic-geometric mean
*provided two numbers (x,y) and an epsilon (e) are entered.
*/
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main (int argc, char **argv) {
//Check for command line argument.
if (argc != 4) {
printf ("Please enter two numbers (x,y) and an epsilon (e)\n");
printf ("as command line arguments for an AGM calculation\n");
exit(1);
}
double e,x,y,an,gn;
x = atof (argv[1]); //First number x.
y = atof (argv[2]); //Second number y.
e = atof (argv[3]); //Number of repetitions e.
double absoluteAnMinusGn; //Continuation condition.
double a = (x + y) / 2; //Normal arithmetic mean.
double g = sqrt (x * y); //Normal geometric mean.
an = (a + g) / 2; //Iteration 1 for calculation arithmetic mean.
gn = sqrt (a * g); //Iteration 1 for calculation geometric mean.
absoluteAnMinusGn = an - gn; //Calculates continuation condition.
if (absoluteAnMinusGn < 0) {
absoluteAnMinusGn = absoluteAnMinusGn * (-1); //Ensures absolute value of continuation condition.
}
printf ("DEBUG IN: x%d, y%d, e%d, absoulteAnMinusGn%d, a%d, g%d, an%d, gn%d\n", x,y,e,absoluteAnMinusGn,a,g,an,gn);//DEBUG CODE
while (absoluteAnMinusGn > e) {
an = (a + g) / 2;
gn = sqrt (a * g);
a = an;
g = gn;
absoluteAnMinusGn = an - gn;
if (absoluteAnMinusGn < 0) {
absoluteAnMinusGn = absoluteAnMinusGn * (-1);
}
}
//printf ("The arithmetric-geometric mean is (%d,%d) for %d\n", a,g,e);
printf ("DEBUG OUT: x%d, y%d, e%d, absoulteAnMinusGn%d, a%d, g%d, an%d, gn%d\n", x,y,e,absoluteAnMinusGn,a,g,an,gn);//DEBUG CODE
return 0;
}
I enter the following on the command line: agm.exe 3 4 5
I get the following output:
DEBUG IN: x0, y10742661112, e0, absoluteANMinusGn1074790400, a0, g1075052544, an-171951648, gn1057505593
DEBUG OUT: x0, y10742661112, e0, absoluteANMinusGn1074790400, a0, g1075052544, an-171951648, gn1057505593
I made a similar program yesterday for calculating an integral using command line inputs that works exactly as intended. The code for that is here:
/*
*This program will calculate a Riemann sum using the
*left hand rule for sin(x)/x.
*/
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main (int argc, char **argv) {
//Check for command line argument.
if (argc != 4) {
printf ("Please enter integral bounds (a,b) and number of intervals (n)\n");
printf ("as command line arguments for a Riemann sum calculation \n");
exit(1);
}
double a,b,i,n,h,riemann,rectangles,answer;
a = atof (argv[1]); //Lower bound of integral.
b = atof (argv[2]); //Upper bound of integral.
n = atof (argv[3]); //Number of intervals.
h = (b - a) / n; //Delta X.
i = 0; //Counts intervals.
//Calculation of Left Hand Riemann Sum.
while (i <= (n - 1)) {
if (a == 0 && i == 0) { //Stops from dividing by zero.
rectangles = 1;
i++;
}
riemann = (sin(a + (i * h))) / (a + (i * h));
rectangles += riemann;
i++;
}
//Finalize answer.
answer = rectangles * h;
printf ("Sin(x)/x for bounds (%f , %f) with %f intervals is approximately %f \n", a,b,n,answer);
return 0;
}
The above program for a left hand Riemann sum outputs correctly, and is almost the same as the code I have for the AGM. Can someone please help me figure out what is going wrong here? I've searched all over and I can't find a solution. I'm aware that the AGM code is probably set up to output an incorrect answer, but my primary concern is fixing my command line argument recognition. I can redo my math later.
The format specifier for printing double is %f. In cases where you didn't provide the right format specifier to process the double, and passed double to %d format specifier - it lead to undefined behavior.(%d expect integral argument not double) (in your case wrong output).
From §7.21.6.3p9 N1570 (c11 standard)
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
I did not test your algorithm, but I found at least three problems in your code. I now list them as follows:
Forgot init your variable, that's why you got a Large Numbers
which is memory undefined data!
No have covert your argv to a integer type.
Wrong format for printf.
I have put my fixed code here, you can test it . if it can run as your expect!
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main (int argc, char *argv[]) {
if (argc != 4) {
printf ("Please enter two numbers (x,y) and an epsilon (e)\n");
printf ("as command line arguments for an AGM calculation\n");
exit(1);
}
// argv is pointer which pointer to pointer
// and argv[1] is a pointer to a string.
// so we need to covert string to int
char *p=NULL;
int x = strtol(argv[1], &p, 10);
int y = strtol(argv[2], &p, 10);
int e = strtol(argv[3], &p, 10);
//Check for command line argument.
double an = 0.0,gn =0.0;
double absoluteAnMinusGn=0.0; //Continuation condition.
double a = (x + y) / 2; //Normal arithmetic mean.
double g = sqrt (x * y); //Normal geometric mean.
an = (a + g) / 2; //Iteration 1 for calculation arithmetic mean.
gn = sqrt (a * g); //Iteration 1 for calculation geometric mean.
absoluteAnMinusGn = an - gn; //Calculates continuation condition.
if (absoluteAnMinusGn < 0) {
absoluteAnMinusGn = absoluteAnMinusGn * (-1); //Ensures absolute value of continuation condition.
}
printf ("DEBUG IN: x%d, y%d, e%d, absoulteAnMinusGn=%f, a=%f, g=%f, an=%f, gn=%f\n", x,y,e,absoluteAnMinusGn,a,g,an,gn);//DEBUG CODE
while (absoluteAnMinusGn > e) {
an = (a + g) / 2;
gn = sqrt (a * g);
a = an;
g = gn;
absoluteAnMinusGn = an - gn;
if (absoluteAnMinusGn < 0) {
absoluteAnMinusGn = absoluteAnMinusGn * (-1);
}
}
printf ("DEBUG OUT: x=%d, y=%d, e=%d, absoulteAnMinusGn=%f, a=%f, g=%f, an=%f, gn=%f\n", x,y,e,absoluteAnMinusGn,a,g,an,gn);//DEBUG CODE
return 0;
}
and then when i run it with some sample number like below show, i got the result .
Just replace the %d(which is a format specifier for integers) with %f(which is the format specifier for double) because you are using a variable of type double, not an integer .
Yes, this is a basic C coding homework problem. No, I am not just looking for someone to do it for me. Considering that this is my first programming class, I'm not surprised that I can't get it to work, and I'm certain there is plenty wrong with it. I just want some help pointing out the problems in my code and the things that are missing so that I can fix them on my own.
Homework Question:
Write a program to read ONLY one integer number (your input must be
one 3 digit number from 100 to 999), and to think of a number as
being ABC (where A, B, and C are the 3 digits of a number). Now,
form the number to become ABC, BCA, and CAB, then find out the
remainder of these three numbers when they are divided by 11.
Assume remainders would respectively be X, Y, and Z and add them
up as X+Y, Y+Z, and Z+X. Now if any of these summations is odd
number, increase it by 11 if the summation plus 11 is less than 20,
otherwise decrease the summation by 11 (this summation operation
must be positive number but less than 20). Finally, divide each
of the sums in half. Now, print out all the resulting digits.
My Code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declare all variables
int OrigNumber;
int x, y, z;
int number;
number = x, y, z;
int sum;
//
printf("Input a three digit number");
//
int c;
c = OrigNumber %10;
//
int b;
b=((OrigNumber - c) % 100)/10;
//
int a;
a = (OrigNumber - (b + c))/100;
//
int abc, bca, cab;
abc = (a*100) + (10*b) + c;
bca = (10*b) + c + (a*100);
cab = c + (a*100) + (10*b);
//
if((number % 2) == 1)
{
if(number + 11 < 20)
number += 11;
else if((100 - 11 > 0) && (100 - 11 < 20))
number -= 11;
}
//
x = abc/11;
y = bca/11;
z = cab/11;
//
sum = (x + y),
(y + z),
(z + x);
}
To start with, you need to read the input. Start with a prompt that includes a carriage return:
printf("Input a three digit number: \n");
Since it's a three digit number, you could add the following line to read the input:
scanf("%3d", &OrigNumber);
The next bit of code works quite well until you get to your if (number % 2) which is meaningless since you didn't really define number - well, you did, but the line
number = x, y, z;
does NOT do what you think it does. If you add
printf("So far I have abc=%d, bca=%d, cab=%d\n", abc, bca, cab);
after you first read in the number and computed those three, you will see you are well on your way.
Note that
number = x, y, z;
Uses a thing called the "comma operator". All the things (a,b,c) are "evaluated" but their values are not returned. At any rate, where you have that line, you didn't yet assign a value to x,y and z.
Is that enough to get your started?
update now that you have had a few hours to mull this over, here are a few more pointers.
Your computation of abc, cab, bca makes no sense. I will show you just one of them:
cab = c*100 + a*10 + b;
Next you need to compute each of x, y and z. Again, here is one of the three:
y = bca%11;
Now you have to make the sums - I call them xy, yz, and zx. Just one of them:
zx = z + x;
Next, to deal with the instruction: "Now if any of these summations is odd number, increase it by 11 if the summation plus 11 is less than 20, otherwise decrease the summation by 11:
if(xy % 2 == 1) {
if(xy + 11 < 20) xy += 11; else xy -= 11;
}
use similar code for all three sums. Then "divide by 2":
xy /= 2;
repeat as needed.
Finally, print out the result:
printf("xy: %d, yz: %d, zx: %d\n", xy, yz, zx);
The amazing thing is that if you did this right, you get the original numbers back...
You could make the code more compact by using an array of values and looping through it - rather than repeating the code snippets I wrote above with different variables. But I suspect that is well outside the scope of what you are expected to know at this point.
Can you take it from here?
#include <stdio.h>
int main()
{
//Declare all variables
int OrigNumber;
int a, b, c;
int abc, bca, cab;
int x, y, z;
int xplusy , yplusz, xplusz;
printf(" A program to read ONLY one integer number.\n Input must be one 3 digit number from 100 to 999 : ");
scanf("%d", &OrigNumber); // Get input from console
if(OrigNumber > 999 || OrigNumber < 100) {
printf("Invalid number. Quiting program. This is error handling. Important while learning programming.");
return 0;
}
c = OrigNumber %10; // digit at unit's place
b=((OrigNumber) % 100)/10; //digit at the ten's place
a = (OrigNumber)/100; //digit at the 100's place. Note: 734/100 = 7. NOT 7.34.
printf("\n Three numbers say A,B, C : %d, %d , %d ", a, b, c);
abc = a*100 + 10*b + c;
bca = 100*b + 10*c + a;
cab = c*100 + a*10 + b;
printf("\n Three numbers say ABC, BCA, CAB : %d, %d , %d ", abc, bca, cab);
x = abc % 11; // Reminder when divided by 11.
y = bca % 11;
z = cab % 11;
printf("\n Three numbers say X, Y, Z : %d, %d , %d ", x, y, z);
xplusy = x + y; // Adding reminders two at a time.
yplusz = y + z;
xplusz = x + z;
printf("\n Three numbers X+Y, Y+Z, X+Z : %d, %d , %d ", xplusy, yplusz, xplusz);
if((xplusy % 2) == 1) {
if(xplusy + 11 < 20)
xplusy += 11;
else
xplusy -= 11;
}
if((yplusz % 2) == 1) {
if(yplusz + 11 < 20)
yplusz += 11;
else
yplusz -= 11;
}
if((xplusz % 2) == 1) {
if(xplusz + 11 < 20)
xplusz += 11;
else
xplusz -= 11;
}
xplusy /= 2; // Finally, divide each of the sum in half.
yplusz /= 2;
xplusz /= 2;
printf("\n Now print out all the resulting digits : %d, %d , %d \n", xplusy, yplusz, xplusz);
return 0;
}
int abc, bca, cab;
abc = (a*100) + (10*b) + c;
bca = (10*b) + c + (a*100);
cab = c + (a*100) + (10*b);
I suggest printing out the numbers at this point in the code.
printf( "%d %d %d", abc, bca, cab );
I think you'll see one of the problems you need to solve.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int n, a, b, c, abc, bca, cab, x, y, z, p, q, r;
scanf("%d", &n);
c=n%10;
b=(n/10)%10;
a=n/100;
abc=a*100+b*10+c;
bca=b*100+c*10+a;
cab=c*100+a*10+b;
x=abc%11;
y=bca%11;
z=cab%11;
p=x+y;
q=y+z;
r=z+x;
return 0;
}
Now if any of these summations is odd number, increase it by 11 if the
summation plus 11 is less than 20, otherwise decrease the summation by
11 (this summation operation must be positive number but less than
20). Finally, divide each of the sums in half. Now, print out all the
resulting digits.
i didnt get the final part, can you explain it more clearly?
I'm designing an algorithm to define a simple method able to find the local maximum of a function f (x) given in an interval [a, b]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.141592653
float funtion_(float a, float x){
float result=0;
result = a * (sin (PI*x));
return result;
}
int main (){
double A = 4.875; //average of the digits of the identification card
double a = 0.0, b =1.0; //maximum and minimum values of the interval [a, b]
double h=0;
double N;
double Max, x;
double sin_;
double inf;
printf ("input the minux value: ");
scanf ("%lf", &inf);
printf ("input the N value: ");
scanf ("%lf", &N);
h= (b-a)/N;
printf("h = %lf\n", h);
x=a-h;
Max = -inf;
do {
x = x+h;
sin_ = funtion_(A, x);
if (sin_>=Max){
Max = sin_;
}
}while (x==b);
printf ("Maximum value: %lf.5", Max);
return 0;
}
The algorithm implements the function f (x) = A * sin (pi * x), where A is the average of the digits of my ID, and inf variable is assigned a number sufficiently greater than the values reached by the function in the interval [a, b] = [0.1].
The algorithm must find the local maximum of the function but it is the maximum returns always zero. do not understand why. What problem may be the logic of my solution?, this problem can be solved by this simple algorithm or some optimization by backtracking is necessary ? Thanks for your responses.
Several problems with this code; probably the most glaring is:
int a = 0, b = 1;
float Max, x;
/* ... */
do {
/* ... */
} while (x == b);
You cannot compare an int and a float for equality. It might work once in a great while due to dumb luck :) but you cannot expect this code to function reliably.
I strongly recommend changing all your int variables to double, all your float variables to double, and all the scanf(3) and printf(3) calls to match. While you can combine different primitive number types in one program, and even in one expression or statement, subtle differences in execution will take you hours to discover.
Furthermore, comparing floating point formats for equality is almost never a good idea. Instead, compare the difference between two numbers to a epsilon value:
if (fabs(a-b) < 0.001)
/* consider them equal */
You might want to scale your epsilon so that it matches the scale of your problem; since float really only supports about seven digits of precision, this comparison wouldn't work well:
if (fabsf(123456789 - 123456789.1) < 0.5)
/* oops! fabsf(3) used to force float */
/* and float can't tell the difference */
You might want to find a good introduction to numerical analysis. (Incidentally, one of my favorite classes back in school. :)
update
The core of the problem is your while(x == b). I fixed that and a few smaller problems, and this code seems to work:
#include
#include
#include
#define PI 3.141592653
float funtion_(float a, float x)
{
float result = 0;
result = a * (sin(PI * x));
return result;
}
int main()
{
float A = 4.875; //average of the digits of the identification card
float a = 0.0, b = 1.0; //maximum and minimum values of the interval [a, b]
float h = 0;
float N;
float Max, x;
float sin_;
float inf;
printf("\ninput the inf value: ");
scanf("%f", &inf);
printf("\ninput the N value: ");
scanf("%f", &N);
h = (b - a) / N;
x = a - h;
Max = -inf;
do {
x = x + h;
sin_ = funtion_(A, x);
if (sin_ >= Max) {
Max = sin_;
printf("\n new Max: %f found at A: %f x: %f\n", Max, A, x);
}
} while (x < b);
printf("Maximum value: %.5f\n", Max);
return 0;
}
Running this program with some small inputs:
$ ./localmax
input the inf value: 1
input the N value: 10
new Max: 0.000000 found at A: 4.875000 x: 0.000000
new Max: 1.506458 found at A: 4.875000 x: 0.100000
new Max: 2.865453 found at A: 4.875000 x: 0.200000
new Max: 3.943958 found at A: 4.875000 x: 0.300000
new Max: 4.636401 found at A: 4.875000 x: 0.400000
new Max: 4.875000 found at A: 4.875000 x: 0.500000
Maximum value: 4.87500
$
You are doing your calculations, in particular the initialisation of h, with integer arithmetic. So in the statement:
h = (b-a) / N;
a, b, and N are all integers so the expression is evaluated as an integer expression, and then converted to a float for assignment to h. You will probably find that the value of h is zero. Try adding the following line after the calculation of h:
printf("h = %f\n", h);
After you've fixed that by doing the calculations with floating point, you need to fix your while loop. The condition x = b is definitely not what you want (I noticed it was originally x == b before your formatting edit, but that's not right either).
Should the while condition be: while(x <= b)
while (x = b);
There is no way to exit the loop. b is always 1.