I am trying to write some functions for Complex type numbers, but I couldn't make this work.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct{
double a; /* Real*/
double b; /* Imaginary*/
}Complex;
Complex Nmbr1,Nmbr2;
int main()
{
Complex NmbrMulti;
printf("Type the value of the real part of the first number\n");
scanf("%d",&Nmbr1.a);
printf("\nType the value of the Imaginary part of the first number\n");
scanf("%d",&Nmbr1.b);
printf("\nType the value of the real part of the second number\n");
scanf("%d",&Nmbr2.a);
printf("\nType the value of the Imaginary part of the second number\n");
scanf("%d",&Nmbr2.b);
NmbrMulti.a = Nmbr1.a * Nmbr2.a - Nmbr1.b * Nmbr2.b ;
NmbrMulti.b = Nmbr1.a * Nmbr2.b + Nmbr2.a * Nmbr1.b ;
printf("\nThe Multiplication : %d+i", NmbrMulti.a);
printf("%d\n", NmbrMulti.b);
return 0;
}
but I get the result 0+i0 , it seems that the problem is with the operations, is there another way to do multiplication for double numbers that I'm not aware of ?
When scanf sees %d, the corresponding argument must be a pointer to int. If the argument is a pointer to double, the code should be %lf.
Reference
http://www.cplusplus.com/reference/cstdio/scanf/
Formatting for double in C is lf rather than d. The latter implies and int.
Related
The objective here is to print the student's average grade as a letter (A for Aprooved, R for Reprooved, or F for Miss, or Falta, in Portuguese), with the average grade value itself, and the student's total presence in classes, using pointers to avg and misses. But after compilation, only the char return value is printed, with 0 on the others.
I tried to print the stored values in the pointers *avg and *presence, but the program takes the student grade values and present values before crashing.
#include <stdio.h>
char situation(float n1,float n2,float n3,int misses, int classes, float
*avg, float *presence);
int main()
{
float *avg, *presence, vet[3];
int f, a, x;
printf("Write the value of your notes \n");
for(x=0;x<=2;x++)
{
printf("Note %d:",x+1);
scanf("%f",&vet[x]);
}
printf("Misses: ");
scanf("%d",&f);
printf("Given: ");
scanf("%d",&a);
char outcome=situation(vet[0], vet[1], vet[2], f, a, &avg, &presence);
printf("With an average of %f and presence of %f percent, your situation is %c",avg,presence,outcome);
return 0;
}
char situation(float n1,float n2,float n3,int misses, int classes, float
*avg, float *presence)
{
char result;
*presence=((classes-misses)/classes)*100;
*avg=(n1+n2+n3)/3;
if(*presence>=0 && *presence<75)
{
result='F';
}
if(*presence>=75 && *presence <=100)
{
if(*avg>=0 && *avg<6);
{
result='R';
}
if(*avg>=6 && *avg<=10)
{
result='A';
}
if(*avg<0 || *avg>10)
{
result='x';
}
}
if(*presence<0 || *presence>100)
{
result='x';
}
return result;
}
I expected the student's total presence and the average grade as a value and letter (A, R, or F), printed on the terminal to the user, but it only returned the char result value.
Your code has one main problem:
float *avg,*presence,
When you a calling
char outcome=situation(vet[0],vet[1],vet[2],f,a,&avg,&presence);
You are passing the address to the pointer you just declared. By changing the value in the function outcome, you are changing the address that avg and presence are pointing to, not the value of the variable.
Try changing to
float avg,presence
This way, when you change the value (using the * operator) you will change the actual variable value.
You may find this that presence still be showing as 0 on the printf. This is because how C works with types in arithmetics operations. Your division has only ints on it, so the result will be a int. Given the result will always be >= 1, the result will be rounded to the int value, which is 0.
To fix that just put a float value in the division and the result will be a float.
Something like:
*presence=((classes-misses)/(classes*1.0))*100;
avg is a float pointer, you are sending it by pointer (&avg) so your function needs to be (int n1,....,float **avg,...)
Try to send avg without the &.
Give him a value before (it is better)
The compiler warning pointed you directly to the problem. You should examine the warning and come to understand what it means and why it was issued.
Your error is here:
float *avg,*presence
These should be declared as float, not float *.
Please give me some feedback on how to make my code better or more efficient. It should convert a decimal integer to binary.
#include <stdio.h>
binarydigits(int div, int dis)
{
int numit;
numit=0;
do
{
++numit;
div /= dis;
}
while (div!=1);
++numit;
return numit;
}
main()
{
int x, nb, i;
printf("\n Input an decimal integer number to be converted: ");
scanf("%d", &x);
fflush(stdin);
if (x==0 || x==1)
{
printf("\n\n %d in binary : %d", x, x);
}
else
{
printf("\n\n %d in binary : ", x);
nb = binarydigits(x, 2);
// the function 'binarydigits' returns how many binary digits are needed to represent 'x'
int remind[nb];
// an array of 'nb' elements is declared. Each element of this array will hold a binary digit
for(i=(nb-1) ; i>=0 ; --i, x/=2)
{
remind[i] = x%2;
}
//this 'for' structure saves the remainder of 'x/2' (x%2) in an element of the 'remind[nb]' array
for (i=nb ; i>0 ; --i)
{
printf("%d", remind[nb-i]);
}
//this 'for' structure prints the elements of the 'remind[nb]' array in increasing order
}
getch();
return 0;
}
Any tips on how to make this better would be nice.
Firstly, binarydigits should have a return type int. This is because you return an integer variable numit at the end of this function. Change your function header to:
int binarydigits(int div, int dis)
Secondly, the main() function needs to have a return type int by definition in C, and C++ for that matter. Without it, your compiler will produce a warning, something similar to:
main.c:18:1: warning: return type defaults to 'int' [-Wimplicit-int]
main()
^~~~
Here is a snippet from the the C11 standard (ISO/IEC 9899:2011) on the definition of the main() function:
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: - Return Type of main()
int main(void) { /* ... */ }
Thirdly, you should remove fflush(stdin) because using the fflush() for stdint is undefined behavior as it is not a part of standard C. From C11 7.21.5.2, fflush works only with output/update stream, not input stream:
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined. - fflush(stdin)
How to make my code better or more efficient?
My advice to you is to stop trying to learn C by trial-and-error method. You should obtain a good book and study it first. It is impossible to create a fast and efficient C program without mastering pointers, bitwise operators and memory manipulations.
Simply, to make your code fast, you should completelly delete your code (I am not going to list all of your bad-practice things here) and start understanding my example:
int main(void){
char *s = (char*)malloc(33);
char *t = s;
int a;
s += 33;
*s = 0;
printf("Enter a number: ");
scanf("%d", &a);
printf("That number in binary: ");
while(a){
*(--s) = a & 1 ? '1' : '0';
a >>= 1;
}
printf("%s\n", s);
free(t);
return 0;
}
Explanation: we have pointer (if you don't know pointers, well you should probably first learn them) s which points to the end of a string. While number from input (number a) is nonzero, we put its last binary digit in the string, decrease pointer and divide a integrally by 2 (this is a >>= 1 instruction). When a is 0, just print the string.
Okay this is actually a very simple code but since I am only starting to learn C, please be patient and help me out. I'll be putting my Questions as comments beside the code so that it easy to relate to which part of the code I have a doubt.
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",output_no);
/*here I wanted to print only the integer part of the output_no */
}
The problem with this is that I had a book and it displayed the value for third no as 0.
And then in another program it says that compile time error is shown.
Second program:
#include <stdio.h>
void main()
{
int x = 5.3%2;
printf("Value of x is %d", x);
}
For this program, the book says that a compile time error will be shown. I fail to understand why that is the case. According to me the output should be 1.
If I were to use the following code instead of the previous code:
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",dec_no);
}
What output should I expect? Do I still get a zero or some unpredictable output?
The problems with using just
printf("Third No:%d\n",output_no);
is that:
output_no gets converted to a double before being passed to printf.
When printf sees %d as the format specifier, it expects an int. When the object being passed is of type double, the behavior is undefined.
When you want to print a truncated integral value of a floating point number, you can do one of the following.
Create a temporary variable of the integral type and assign to it the floating point number.
int temp = output_no;
printf("Third No:%d\n", temp);
Explicitly cast the floating point number to an integral type.
printf("Third No:%d\n", (int)output_no);
printf("Third No:%d\n",dec_no);
What output should I expect? Do I
still get a zero or some unpredictable output?
As of the printf function is concerned,
When you try to print an integer value with format specifiers that are used for float (or) double and vice the versa the behaviour is unpredictable.
But it is possible to use %c to print the character equivalent of the integer value. Also using of %d to print ASCII value (integer representations) of character is acceptable.
Second program: For this program, the book says that a compile time
error will be shown.
According to C Reference manual
7.3.3 expression % expression
The binary % operator yields the remainder from the division of the first expression by the second. Both operands must be int or char, and
the result is int. In the current implementation, the remainder has
the same sign as the dividend.
Here in your case you are providing one value 5.3 so it is neither char nor int so that is why it generates compilation error.
If you still want to run that program you can do that by using fmod() function.
Try this code :
#include<stdio.h>
#include<math.h>
void main()
{
float x=5.3;
int c =2;
printf("Value of xremainer is %lf",fmod(x,c));
}
Compile it as :
$gcc test.c -lm
#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.
Program only displaying the 32 for when I have it print "NewTemp"
NewTemp = 32 + input * 180/100; this part seems like the main problem
#include <stdio.h>
float celsius(float input) {
float NewTemp;
**NewTemp = 32 + input * 180/100;
printf("Please enter the temperature value to convert to fahrenheit\n");
scanf("%f", &input);
printf("The temperature in celsius is: %f\n", NewTemp);
return NewTemp;
}
int main(void){
float CelToFahren, input;
CelToFahren = celsius(input);
}
You do the math before you read the input. You need to do it the other way around.
Also, there's no reason to pass a meaningless and uninitialized value to the celsius function.
Lastly, 180/100 is 1 remainder 80 because when you divide two integers, you get integer division. You can use 180.0/100.0.
Basically, you need to learn C.