I have to create a code that determines the smallest of three numeric values.
Macro MINIMUM3 should use macro MINIMUM2 (the difference btwn two numeric values) to determine the smallest number. the input values come from the user input. I am not very familiar with using macros and my textbook doesn't really help in showing me an example of how they can work together to carry out their function. The code below is the work in progress that I have so far but I am running into errors on lines 3, 13, 16, and 20.
#define MINIMUM2 (a,b) (a < b ? a:b)
#define MINIMUM3 (a,b,c) (MINIMUM2(a,b) c? MINIMUM (a,b) :c)
int main (void) {
int x,y,z;
int temp;
printf("Please enter three numbers\n");
scanf("%d%d%d, &x&y&z);
temp = MIN(x,y,z);
printf("The smallest number entered is:\n");
printf("%d", &temp);
getchar ();
return0;
}
You have a couple of issues in your code:
MINIMUM3 uses MINIMUM instead of MINIMUM2
The logic of MINIMUM3 is broken
You need to remove spaces after macro names
You are missing a closing double quote and commas in call of scanf
You are using MIN in place of MINUMUM3
You are passing an address of temp to printf
Here is how you can fix this:
#define MINIMUM2(a,b) (a < b ? a:b)
#define MINIMUM3(a,b,c) (MINIMUM2(MINIMUM2(a,b),c))
int main (void) {
int x,y,z;
int temp;
printf("Please enter three numbers\n");
scanf("%d%d%d", &x, &y, &z);
temp = MINIMUM3(x, y, z);
printf("The smallest number entered is:\n");
printf("%d", temp);
getchar ();
return0;
}
Demo.
You can improve your macros by enclosing each parameter in parentheses:
#define MINIMUM2 (a,b) ((a) < (b) ? (a) : (b))
Your definition of the MINIMUM3 macro will lead to a syntax error. You should try something like
#define MINIMUM3(a, b, c) MINIMUM2(MINIMUM2(a, b), c)
or
#define MINIMUM3(a, b, c) MINIMUM2(a, MINIMUM2(b, c))
Also make sure to call MINIMUM3 in main, not MIN.
Related
Thank you to anyone reading this , I have a problem with a part of my code , I'm learning to do functions, and functions that are named enter and get_random work fine.
Now i want to add function addsum, but for some reason when i run the code with it, the debugger stops me when the for loop of checking the column finishes and the for loop that loops row should start .
Could anyone tell me what I am doing wrong? i only know the bare essentials of pointers, maybe that is the solution to my problems? thanks in advance.
This is the message from the debugger
passing argument 4 of ‘addsum’ makes pointer from integer without a cast [-Wint-conversion]
#include<math.h>
#include<stdio.h>
#include<stdlib.h> // libraries added from example
#include<time.h>
//(*) For a square matrix calculate the sum of elements under the main diagonal excluding it.
#define A -10
#define B 10
int main(){
void enter(int *x,int *y);
int get_random(int lbound,int ubound);
int addsum(int ro, int co, int s, int arr[ro][co]);
int r;
int c;
int row,col,sum=0;
enter(&r,&c);
srand48(time(NULL)); //Call srand48 with current time reported by `time` casted to a long integer.
// srand48 is used to reinitialize the most recent 48-bit value in this storage
int array[r][c]; // we decided its gonna be r rows and c columns
for (row=0;row<r;++row) // we cycle numeration of rows of matrix
{
for(col=0;col<c;col++) // we cycle numeration of columns of matrix
{
array[row][col]=get_random(B,A);// filling array with random numbers, taken from example
printf("%d ",array[row][col]);
addsum(row, col, sum, array[row][col]);
}
printf("\n"); // this is to break line after row 1,2 col 3, so it looks nicer
}
printf("\n");
printf("sum of array: %d\n", sum);
return 0;
}
void enter(int *x,int *y){ // we have to use pointers if we want more then one return from a function
printf("How man rows in array? ");
scanf("%d", x); // we use x instead of &x because we need the adress of the number not the value
printf("How man columns in array? ");
scanf("%d", y); // we use y instead of &y because we need the adress of the number not the value
}
int get_random(int lbound,int ubound)
{
return rand()%(ubound-lbound+1)+lbound; // function for generating random numbers
}
int addsum(int ro, int co, int s, int arr[ro][co])
{
if (ro>co){ //since we want the sum numbers below the diagonal row>col must be true
s=s+arr[ro][co];// if row>col than we add the number to our sum
return s;
}
}
I have tried to rewrite the function in several different ways, but i dont think its my syntax thats the problem.
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 3 years ago.
Improve this question
I want this program to choose the largest number and then based on user's input to square it or put it on cube. I know there's pow math function that can be used but I'm trying to play with functions as much as possible to get the hang of it.
I already made one program that correctly shows me the largest number, and it works well. I didn't want to copy it so I wrote it from scratch and now I'm checking everything, it's almost same but shows wrong result even for MAX. What do I need to fix?
int max(int NUM1, int NUM2, int NUM3; )
{
int NUM1, NUM2, NUM3;
int X;
if (NUM1 >= NUM2) {
X = NUM1;
} else {
X = NUM2;
}
;
if (NUM3 >= X) {
X = NUM3;
}
;
return X;
}
int square(int MAX)
{
return MAX * MAX * MAX;
}
int cube(int MAX)
{
return MAX * MAX;
}
int main()
{
int NUM1, NUM2, NUM3, MAX;
char A;
printf("ENTER 3 NUMBERS: ");
scanf("%d %d %d", &NUM1, &NUM2, &NUM3);
MAX = max(NUM1, NUM2, NUM3);
printf("LARGEST NUMBER: %d", MAX);
printf("DO YOU WANT IT SQUARED OR CUBED? (S/C) ");
scanf("%c", &A);
if (A = "S") {
printf("SQUARE: %d", square(MAX));
} else {
printf("CUBE: %d", cube(MAX));
}
return 0;
}
There are several errors and problems in your source. You would have found most of them if you had set the warning level to the max. Especially as a beginner you should do that, for example for GCC use the options -Wall -Wextra and if you like -pedantic.
There is no #include <stdio.h> which declares printf() and scanf().
The parameter list of max() has a trailing semicolon that (at least) irritates GCC. Clang correctly moans about it. It has to be removed.
The function max() has both parameters and local variables NUM1, NUM2, and NUM3. The latter shadow the former, in other words you can't access the arguments. Additionally the values of the local variables are undefined.
There are empty statements (a single semicolon ;) after the ifs in max(). They don't do evil but disturb the casual reader.
The formulas of square() and cube() are swapped.
Add a newline character after your result output like this: "LARGEST NUMBER: %d\n" to separate output and following prompt visually.
scanf() is quite tricky to use and best avoided at all. This is true especially for reading single characters. I had to insert a blank before "%c" to skip the newline of the input line of the numbers.
The expression (A = "S") is an assignment of a pointer const char * to a character char. But you want to compare two characters so it has to be (A == 'S'). C differentiates between character literals and character array literals.
Choose lower case names for functions and parameters and variables. As others mention all upper case names are reserved for constants per convention.
Please adapt a good code style (there are lots of them if you ask your favorite search engine) and stick to it.
void main()
{
int a, b, r;
//Finf GCD by Eucledian algorithm
scanf("%d %d", &a, &b);
for( ; b == 0; (a = b), (b = r)){
r = a % b;
printf("GCD is %d", a);
}
printf("GCD is %d", a);
}
Somehow this doesn't work.
I assign a to b and b to r, but this doesn't seem to change the value of a or b.
This for(;b==0;(a=b),(b=r)) sets up the for-loop like this
do nothing to init anything
as long as b equals 0 do the loop body
between loop body executions first copy value of b to a,
then copy value of r to b
Note that the loop will never execute if b starts off non-zero.
Otherwise the loop will stop executing as soon as b becomes non-zero, from being updated with value of r.
(This is somewhat compiling an answer from comments, in order to get this out of the list of unanswered questions. Credits to dddJewelsbbb. I offer to delete this if they make an answer and ask me to.)
Find the corrected working code below, which changes the loop condition:
#include <stdio.h>
void main ()
{
int a, b, r;
//Finf GCD by Eucledian algorithm
scanf ("%d %d", &a, &b);
for (; r > 0; a = b, b = r)
{
r = a % b;
}
printf ("GCD is %d", a);
}
Test by giving inputs: 16, 12
16
12
GCD is 4
Code explanation:
The code is the direct implementation of Euclid's algorithm to find GCD. Here the divisor (one of the number) is used to obtain a remainder (after dividing the second number as dividend). Next, the remainder becomes the divisor and the earlier divisor becomes the dividend and this process continues till remainder is zero.
There is plenty of scope in the code to make it more elegant and handle corner cases. I corrected the exact same code as minimum as possible to spot the exact error (which was in the for loop condition).
Check the image
This is my 1st post so have that in mind while reading my question.
I have an exam of a colloquium but my code does not provide me the correct result.
So if anyone could help me that would be great. :)
These are the informations that are provided in the exam:
A function y=f(x)=ax^2+bx+c
We have to find the surface that is below the chart but keep in mind that dx(Delta X)=B-A and the height goes like this: A,A+dx,A+2dx, .... , B-dx.
As dx value gets lower the surface will be more accurate.
You have to write the program so that the surface with precision 0.001
This is my code so could someone who is good in C check it please.
Thank you.
#include <stdio.h>
#include <math.h>
int main()
{
int a,b,c;
double A,B,dx,p,D,q,x,y,nv,nv1,nv2,sv;
do{
printf("Insert a & b: "),scanf("%lf %lf",&A,&B);
} while(A<1 || B<1);
nv=dx=B-A;
do{
printf("enter odds: "),scanf("%d %d %d",&a,&b,&c);
p=(-b)/2;
D=sqrt(pow(b,2)-4*a*c);
q= -D/4*a;
} while( a<0 || p<0 || q<0);
do{
sv=nv;
dx/=2;
nv=0;
for(x=A;x<p;x+=dx)
for(dx=B-A;dx<q;dx/=2)
nv1+=x*dx;
for(y=p;y<=B;y+=dx)
for(dx=q;dx<B;dx/=2)
nv2+=y*dx;
nv=nv1+nv2;
}while(fabs(nv-sv)>0.001);
printf("The surface is %lf",nv);
return 0;
}
You want to find the approximation of a definite integral of a quadratic function. There are several issues with your code:
What is the restriction of A ≥ 1 and B ≥ 1 for? A parabola is defined over the whole abscissa. If anything, you should enforce that the input is numeric and that two values were given.
You don't need to find the vertex of the parabola. Your task is to create small rectangles based on the left x value of each interval as the image shows. Therefore, you don't need p and q. And you shouldn't enforce that the vertex is in the first quadrant on the input without indication.
Why are the coefficients of the parabola integers? Make them doubles to be consistent.
Because you don't need to know the vertex, you don't need to split your loop in two. In your code, you don't even check that p is between A and B, which is a requirement of cour code.
What is the inner loop for? You are supposed to just calculate the area of the current rectangle here. What's worse: you re-use the variable dx as iteration variable, which means you lose it as an indicator of how large your current interval is.
The repeated incrementing of dx may lead to an accumulated floating-point error when the number of intervals is large. A common technique to avoid this is to use an integer variable for loop control and the determine the actual floating-point variable by multiplication.
The absolute value as a convergence criterion may lead to problems with small and big numbers. The iteration ends too early for small values and it may never reach the criterion for big numbers, where a difference of 0.001 cannot be resolved.
Here's a version of your code that puts all that into practice:
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c;
double A, B;
printf("Lower and upper limit A, B: ");
scanf("%lf %lf", &A, &B);
printf("enter coefficients a, b, c: ");
scanf("%lf %lf %lf", &a, &b, &c);
double nv = 0;
double sv;
int n = 1;
do {
int i;
double dx;
sv = nv;
n *= 2;
dx = (B - A) / n;
nv = 0;
for (i = 0; i < n; i++) {
double x = A + i * (B - A) / n;
double y = a*x*x + b*x + c;
nv += dx * y;
}
} while(fabs(nv - sv) > 0.0005 * fabs(nv + sv));
printf("Surface: %lf\n", nv);
return 0;
}
The code is well-behaved for empty intervals (where A = B) or reversed intervals (where A > B). The inpt is still quick and dirty. It should really heck that the entered values are valid numbers. There's no need to restrict the input arbitrarily, though.
#include <stdio.h>
#define PI 3.14159
int Circle (int);
int Rectangle (int, int);
int main()
{
int a;
int b;
int c;
int d;
int area;
int AreaOfCircle;
int AreaOfRectangle;
int area1;
printf("Program to calculate area\n");
printf("1 - Circle\n");
printf("2 - Rectangle\n");
printf("\n");
printf("What option = \n");
scanf("%d", &a);
if(a=1)
{
area=Circle(b);
printf("Area= %d\n", area);
}
else if(a=2)
{
area1=Rectangle(c,d);
printf("Area= %d\n", area1);
}
return 0;
}
int Circle (int b)
{
int area;
printf("radius= \n");
scanf("%d", &b);
area=PI*b*b;
return area;
}
int Rectangle(int c, int d)
{
int area1;
printf("length= \n");
scanf("%d",&c);
printf("width= \n");
scanf("%d",&d);
area1=c*d;
return area1;
}
//I want to ask if my coding is ok .. but as I run it the output only ask for radius which is the calling function for circle .. but if i want to call rectangle the output also shows calculation for circle .. can someone help me to spot the mistake .. by the way this is my first coding about calling function and I just started learning coding c last month .. T-T
With C you use == to evaluate (e.g. if (x == 1)). "=" is assignment, so you'll always hit the first block.
Also, you're accepting parameters which you're then modifying, which is not good practice. Consider declaring your variables at usage time also, the "everything at the top of the block" paradigm is very dated.
This question is not about functional programming, this is an example of imperative programming.
Also, your input being poured directly into an integer is not bounds checked, consider a switch/case so you can add a default of "invalid input" and extend to different shapes in the future.
Yes bro just make if(a==1) and else if(a==1).
You've used the assignment = operator instead of the comparison == operator.
A statement like
if(a=1)
will assign a value of 1 to a and check then check for the non-zero value of a [which always evaluates to TRUE].
Instead, what you want is
if (a == 1)
which evaluates to TRUE if a contains 1. Same for other comparison(s) also.
Note: In your int Circle (int b) case you're storing the result to an int, which will truncate the result of a double/float multiplication. To get the exact value, make the area as float or double and use %f/ %lf format specifier.
Next, as per the logical part, you don't need to pass b, c, d as parameters to the called functions. Simply a local variable in the functions would do the job.