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
Related
#define PI = 3.141593
#define G = 6.67259E-11
#define g = 9.80665
#define M = 5.972E+24
#define r = 6378000
#define h = 220
#include <stdio.h>
#include <math.h>
int main(void)
{
int value;
value =sqrt((G/M)/(r+h))
printf("This is the tangential speed:") value;
return 0;
}
I am very new to coding, and my program is giving me several errors in code blocks, can anyone give me some guidance?
Remove the = from all the #define statements. They are preprocessor macro definitions, not assignment statements, and they do not use equal signs.
Change int value to double value, to use floating-point instead of integers.
Add a ; after value =sqrt((G/M)/(r+h)). Statements in C generally end with a semicolon.
Change printf("This is the tangential speed:") value; to printf("This is the tangential speed: %g.\n", value);. printf is a function call, not a statement, so you pass everything it needs inside a set of parentheses. The string is a format string; it contains both literal text you want printed and conversion specifications like %g that tell it to convert an argument to a string. %g tells it to convert a double argument to a general floating-point display form.
I see two problems:
Smallest problem, but might be significant, is that I assume you want value to be a float or double instead of an int, thus replace
int value;
by
float value;
The print statement is incorrect:
printf("This is the tangential speed:") value;
Assuming value is a float, change it to
printf("This is the tangential speed: %f\n", value);
\n makes a new line.
And of course don't forget the remark by chux.
Im new to C and I really don't know know what I'm doing wrong.
The issue that I am having is I'm supposed to ask 3 questions of the user using scanf. I'm supposed to ask the user for an integer, a positive real number and a non negative number and then calculate the numbers into XX.XX using %.2f.
//pre-processor directives
#include <stdio.h>
#include <math.h>
//main function
int main()
{
//declare variables
int smp1,smp2, smp3,total;
printf("sample 1?\n"); // positive integer
scanf("%d", &smp1);
printf("sample 2?\n"); //positive real number
scanf("%f",&smp2);
printf("sample 3?\n"); // non negative number
scanf("%u", &smp3);
total = (smp1 + smp2 / smp3);
printf("The final result is %.2f",total);
//end of main
return 0;
}
No matter what I put in there my result ends up being 0.00. It won't even do simple addition and I don't know enough to know why.
Your main issue is that you declare all your variables as ints, but smp2 and total must hold floating point values.
Change your declarations to
int smp1;
double smp2, total;
unsigned int smp3;
This way, the types of the variables match up with the conversion specifiers used in the printf and scanf calls.
Types matter in C, and it's up to you that the types of the arguments in each printf and scanf call match up with the conversion specifiers.
Check your compiler documentation on how to enable warnings (even better, to treat all warnings as errors). Most compilers should warn about type mismatches like this, but sometimes you have to set a flag in order for those warnings to appear.
This is not homework, but my last assignment made it clear that I didn't clearly understand pointers when coding C.
Therefore, I tried to type a simple program using pointers just to invert an integer in a function, so I could figure out where the gap in my understanding is.
Apparently, I've arrived at it, but I still cannot figure out what I am doing wrong.
My source code is below.
#include <stdio.h>
float invert(int *num);
void main (void)
{
int num;
float a;
printf("enter an integer \n");
scanf("%i", &num);
printf("Number entered %i \n", num);
a=invert(&num);
printf("This is the invse from main %f \n", a);
}
float invert(int *num) /* function inverts integer */
{
float invse;
printf("num is %i \n\n", *num);
invse = 1/(float)num;
printf("invse is %f \n\n", invse);
return(invse);
}
My thinking was that I used the pointer to direct the computer to use the value stored at the address for num in the function invert(). The pointer appears in the variable declaration. I cast the value stored at that pointer as a float, so I could invert it, and store it in a local variable.
The problem appears to be in the local variable assignment. My compiler returns "invert.c:29:2: error: pointer value used where a floating point value was expected
invse = 1/(float)num;
^
Apparently my code indicates a pointer value for inverse, but I declared it as a float, which I find confusing.
Any help is appreciated. This will save me on completing my larger set of code for my assignment, which I did not post here.
Thanks.
Judging by the printf call inside invert
printf("num is %i \n\n", *num);
you already know that in order to access the value passed to invert for inversion you have to dereference num pointer: *num.
If so, then why aren't you dereferencing num when you perform the inversion itself?
invse = 1/(float)num;
I mean, if you are the one who wrote that printf, you should also realize that the actual inversion should be done as
invse = 1 / (float) *num;
or, alternatively, as
invse = 1.f / *num;
On top of being incorrect your original variant is illegal: you are not allowed to convert pointers to floating-point types in C, which is the reason for the error message.
P.S. From the bigger picture point of view, there's no real reason to pass that the number to invert by pointer. Passing the immediate value would make more sense
float invert(int num)
{
...
In that case you, of course, don't have to dereference anything inside invert.
#include<stdio.h>
float func (float t, float y){
return y ;
}
int main (){
float t0,y0,t,y;
printf ("the value of t: ");
scanf ("%f",&t0);
printf ("the value of y: ");
scanf ("%f",&y0);
t=t0;
y=y0;
static int n=0;
// t[0]=t0;
// y[0]=y0;
for (n=0;n<=3;n++){
y[1]=y[0];
printf ("value of y %f %f \n",t,y);
}
return 0;
}
The error is:
Building prog.obj.
D:\master\c language\ch3\prog.c(166): warning #2117: Old-style function definition for 'main'.
D:\master\c language\ch3\prog.c(182): error #2144: Type error: pointer expected.
D:\master\c language\ch3\prog.c(182): error #2144: Type error: pointer expected.
*** Error code: 1 ***
You cannot array index something that is not an array, or a pointer into an array.
Your y and t floats are not pointers into arrays in your program.
You should make them float *y, *t into pointers so you can point them into array.
Change float t0,y0,t,y; to float t0,y0,*t,*y;
and
t=&t0; //assign address of t0 to t
y=&y0;
Change printf ("value of y %f %f \n",t,y); to
printf ("value of y %f %f \n",*t,*y); //note to dereference t and y here, to get their values
Here's a example of your program I fixed to work
The 'Old-style function definition for main()' message means that you've not given a prototype definition. The correct forms are:
int main(void) { ... }
int main(int argc, char **argv) { ... }
The version int main() is fine in C++, but not strictly a prototype in C, and hence gets the 'old-style' tag.
The other messages are more inscrutable; the line numbers do not correspond to the code you show. However, as Tony The Lion notes in his answer, the line
y[1] = y[0];
is erroneous since y is not an array. There is room to think that should be:
y = y0;
and you'd need a companion:
t = t0;
in order to have defined values printed in the printf() statement.
Even with these changes, the code does not make a lot of sense. However, given that you removed 150-odd lines, we can suppose that the missing code would make more sense.
There is no need to make n into a static variable; it is better not to do so.
Please make sure, in future, that your error messages correspond to the source code you post, not to some variant version of the code you post. The line numbers should not be as large as 166 or 182; they should be single digit numbers or small double digit numbers. But even more importantly, they should match the code!
today,I write some code to test unsigned int.
#include <stdio.h>
int sum_element(float ele[], unsigned int len);
int main(void){
float ele[] = {1.1,2.2,3.3};
float sum = sum_element(ele,3);
printf("sum is %f\n",sum);
return 0;
}
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f, i=%d\n",sum,i);
sum += ele[i];
}
return sum;
}
in this example, i have a mistake, the type of variable sum, should be float, but i write int, the compile command:
gcc test.c -o test
and i run this code
./test
the output of the function sum_element is:
sum=0.000000, i=1
sum=0.000000, i=1
sum=0.000000, i=1
and then i found the mistakes, and i change the type of sum to float, then compiled again,
and when i run it, the output is :
sum=0.000000, i=0
sum=1.100000, i=1
sum=3.300000, i=2
this time, the output like normal,but in first output, why the variable of i is always the same value of 1, can someone tell me?
Nothing to see. You invoked undefined behavior by passing the wrong type to printf, so all output of the program is meaningless. The %f format specifier requires an argument of type double (by the way, float would automatically promote to double in this context, so float would be okay too), but you passed it an argument of type int.
You have to understand how va_arg work. Printf is a function that take a undefined number of arguments. The problem is that those arguments are not typed.
When you specify int, double, ect... the compiler assign differente number of bytes (in a specific order) depending on the arguments. So when you call a function that has type argument, the function know how it should read those bytes.
Here it cannot know since it isn't type. So the printf function is going to believe what you give it. If you ask for example for a 4 bytes when you real value is 8 bytes, the function will read the first 4 bytes believing it the value you ask for. But then the next value you try to match will start with the next 4 bytes. Wich will give you garbage.
You can try to do 2 printf, and you will see that the value of i is actually the good one. Only the way to read it was wrong.
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f\n",sum);
printf("i=%d\n",i);
}
return sum;
}
Hope this can help.
EDIT:
Maybe a example is easier to understand. Try this function:
int sum_element(float ele[], unsigned int len){
int sum=24222.55455555; //mistake,should be : float sum = 0.0
char c = 0 ;
for(i=0;i<= len-1;i++){
printf("sum=%f, n= %d n2 = %d\n",sum,i,c);
}
return sum;
}
You should get a interesting value for n2.
I think the answer is that in the first case, the value being printed is not that of i at all. Two parameters are passed to printf which then reads two off. Those passed in are two ints, and then a double and and int are read off. Because the double is read off the stack first, when the int is read it is not from where the value of i was passed, hence the bogus value. Most likely the double covers enough of the stack to include both the passed ints.
Of course, results may vary, being undefined.