I apologies in advance if there is a stupid error in this code, but I can't seem to trouble shoot it. My problem is this, I compile with GCC-8 (installed on Mac via home-brew), then execute in the terminal. When using int do define variables s & a, I get zeros as output using the print statements below. If I declare s & a variables as double I still get zeros for the first two print statements, and 1024 for the last print statement. I'm just lost as to what is going on. Appreciate any help!
/* square code */
#include <stdio.h>
int main() {
int s, a;
printf("enter the length of your square \n");
scanf("%f", &s);
a= s * s;
printf("the area of your square is %f cm using f placeholder \n", a);
printf("the area of your square is %lf cm uning fl placeholder\n", a);
printf("the area of your square is %d cm using d placeholder \n", a);
return(0);
}
int s;
scanf("%f", &s);
If s is an int then you need to scan it in like an int using "%d" instead of "%f". What you are doing is undefined behavior, both in scanf() and printf(). An integer needs to be scanned and printed as an integer.
I think the misunderstanding is that you treat the conversion specifiers %d and %f as defining only the output formatting, regardless of the type of value passed.
Actually each conversion specifier is tightly coupled with a particular type of argument it will accept; For example, %d is defined for integral types only, and all other types like floating point or string used together with %d will yield undefined behaviour (cf, for example, cpp-reference of printf for a more detailed explanation).
So double f=1.2;printf("%d",f) will not format a floating point value 1.2 as integral (someone might expect 1 being the output); It rather yields undefined behaviour, having any output (even no output), a crash, a... whatever.
Same applies to scanf-format specifiers, of course.
So if data type is int, use %d; if data type is double, use %f.
In your code you use s as an int, and when you use scanf you are using %f instead of %d. That's the reason why you are getting the first two outputs as a zero.
As for the third output, you will get the expected value, because in that case you are correctly using %d. See the code below:
int s;
printf("enter the value");
scanf("%d", &s);
printf("the area of square is=", s*s);
Hey guys thanks so much for the help. Before checking back this morning I tried one more thing, and alas it was a stupid error.
When declaring "double s,a", I realized my scanf() function was using scanf("%f",s) as opposed to the correct scanf("%lf", s)".
Also thanks for the help for use of %d when using "int s,a".
Related
I am trying to find out how percentages are calculated within C, and specifically I am trying to find out how much taxes you get from user input, if the tax would be 21%.
But after trying the code in the terminal with input : 130,
which means I want 21% of 130$, it gives me a negative value of -858993459
How do Ifix this or where did I go wrong?
All of my google searches come up empty too, but probably because I am not using the correct phrasing so all info is welcome.
#include <stdio.h>
double get_tax_amount(double price_including_taxes)
{
return price_including_taxes *0.21;
}
int main()
{
printf("What was your price? ");
double price;
scanf("%d", &price);
printf("The tax price is: %d", get_tax_amount (price));
}
You’re using the wrong conversion specifier in both scanf and printf. To read a double value with scanf you need to use %lf and to print a double value with printf you need to use %f.
Because of how those functions work, they don’t know the number, type, or order of arguments you’ve actually passed to them - they just see a sludge of bytes on the stack or a sea of argument registers. The only way for them to know what arguments they should expect is through what you specify in the format string.
%d is used to read and print int types, %c for individual characters, %s for strings, etc.
Try "%lf" instead of "%d". "%d" is expecting an integer, which conflicts with variable type "double".
The variable type double should use %lf in scanf function, and %f in printf function.
I'm preparing for my graduation test and I have some questions regarding the c programming language. I will combine two of these questions which I have answers for, but I don't really understand them. The first question is select the correct expression that outputs the value of the i-th element of the array and these are the possible answers:
(note that the code for both questions is the same)
printf("%f",B[i]);
printf("%f",&B[i]);
printf("%f",B+i);
printf("%p",*(B+i));
printf("%f",*(B+i));
The second question is select the correct expression that inputs the value of the i-th element of the array
scanf("%f", B[i]);
scanf("%f", B+i);
scanf("%p", B+i);
scanf("%f", &B[i]);
scanf("%f", *(B+i));
I tried to compile and run a program that simulates these questions. The scanf part works for the answers 2-5 and all of the printfs print out a zero except the 4th one (of course after input).
float *B;
int n;
B=calloc(n,sizeof(float));
Your understanding of which answers are correct are flawed.
To print a value of type float using printf, you need to use the %f format specifier and pass a value of type float. To read a value of type float with scanf, you also use the %f format specifier but pass a value of type float *.
Regarding array indexing, the notation A[N] is exactly equivalent to *(A + N) and has the type of the array element, and &A[N] is exactly equivalent to A + N and has type pointer to array element.
Based on that, we have the following:
printf("%f",B[i]); // Correct
printf("%f",&B[i]); // Incorrect, passing a float *, expected float
printf("%f",B+i); // Incorrect, passing a float *, expected float (same as prior)
printf("%p",*(B+i)); // Incorrect, %p is used to print a pointer (expects a void *)
printf("%f",*(B+i)); // Correct
scanf("%f", B[i]); // Incorrect, passing a float, expected float *
scanf("%f", B+i); // Correct
scanf("%p", B+i); // Incorrect, %p is used to read a pointer (expects a void *)
scanf("%f", &B[i]); // Correct
scanf("%f", *(B+i)); // Incorrect, passing a float, expected a float *
float
There are 2 ways to printf a float and 1 way to scanf them.
printf("%f", my_float);
printf("%lf", my_float); // works fine but bad style
scanf("%f", &my_float);
(In the oldest C standard, printf didn't allow %lf)
float*
There is one way to printf the pointer itself:
printf("%p", ptr);
It doesn't make sense to read a pointer with scanf, but you can read to the memory pointed-at by the pointer ptr as:
scanf("%f", ptr); // no & needed, it is already a pointer
Everything else from your examples doesn't make much sense. Printing an address is not printing a float. Applying various forms of arithmetic on the pointer such as &B[i] versus *(B+i) have nothing whatsoever to do with the the printing.
Suppose,"5181 2710 9900 0012"- is a string of digits.I need to take one single digit at a time as input from the string of number without space to make arithmatic operations . So, i write that,
int a[20];
for(int i=0;i<16;i++)
{
scanf("%d",&a[i]);
}
but it didn't give me expected result. But when i use "%1d"instead of "%d",it gave me the expected result. so, how it works?
Since scanf is the inverse of printf, you could verify this by printing any number with the modifier (just a little tip).*
In general, the number before the format is a 'width' modifier. In this case it means you're only reading one byte into a number. If you specify %d, it may be a number of arbitrary length.
Example:
#include <stdio.h>
int main() {
int a;
sscanf("1234", "%d", &a);
printf("%d\n", a); // prints 1234
sscanf("1234", "%1d", &a);
printf("%d\n"m a); // prints 1
}
*) this appears to be false for this particular case. Makes sense that numbers are not truncated when specifiying a %d format, though, since that would change the meaning of the number. However, for many cases you could try what printf would do to predict scanf's behavior. But of course, reading the manual or docs on it is always the more helpful approach :)
When I try to use scanf
int main() {
int x1,x2,x3,y1,y2,y3;
printf("Enter 3 pairs of positive integers separated by spaces:\n");
scanf("%u %u %u %u %u %u", &x1, &y1, &x2, &y2, &x3, &y3);
I get the program running, like for an input.
Then I put the input, but it prints the "enter 3 pairs..." and does nothing
why is that?
%u is unsigned integer. %d or %i is signed integers. Please take care of these quirks and gotchas in C. Be careful to oblige to correct format specifiers.
Maybe you have to enter values; it is the goal of scanf.
By the way, your program contains an undefined behavior : %u mismatchs with int pointers. Use rather %d/%i format in printf. An other solution is to declare your variables as unsigned int type, to match with the printf format. Moreover, a part of your source code is missing.
You might find it more convenient to use fgets instead of scanf. The eclipse terminal is a little funky.
Refer to this post
I created a very simple progam whith a menu,
that take a value, then memorize it into the
local variable value, and finally with the
second option the progam prints the value.
my question is:
Why does the program work only if I add an "h"
to the scanf parameter?
In other words: what kind of relation there is
between scanf() and my local int value variable?
thanks!
p.S. (I used Dev-C++ (GCC) to compile it.
With Visual Studio it works)
#include <stdio.h>
main () {
int value = 0;
short choice = 0;
do {
printf("\nYour Choice ---> ");
scanf("%d", &choice); /* replace with "%hd" and it works */
switch (choice) {
case 1:
printf("\nEnter a volue to store ");
scanf("%d", &value);
getchar();
printf("\nValue: %d", value);
break;
case 2:
printf("\nValue: %d", value);
break;
}
} while (choice < 3);
getchar();
}
With scanf, the "h" modifier indicates that it's reading a short integer, which your variable choice just happens to be. So the "%hd" is necessary to write only two bytes (on most machines) instead of the 4 bytes that "%d" writes.
For more info, see this reference page on scanf
The variable choice is of type short so that's why you need the %h specifier in scanf to read into it (in fact you don't need the d here). The int type just requires %d. See the notes on conversions here
You're reading into a short. The h is necessary because %d is the size of an int by default. See this reference page on scanf.
It looks like your problem is that choice is a short, which is (generally) 2 bytes long, while %d expects an integer, which is (generally) 4 bytes long… So the scanf clobbers whatever comes after choice on the stack.
choice is a short and %d specifies an int.
When you specify %d, scanf has to assume that the associated argument is a pointer to an int sized block of memory, and will write an int to it. When that happens it will likely be writing to data adjacent to but not part of choice and the results are undefined and probably not good! If it works in one compiler and not another that is simply the nature of undefined behaviour!
In GCC -Wformat should give you a warning when you make this error.
From the comp.lang.c FAQ:
Why doesn't the code short int s; scanf("%d", &s); work?
Someone told me it was wrong to use %lf with printf. How can printf use %f for type double, if scanf requires %lf?
%d is for reading an int, not a short. Your code never really "worked" -- it just appears that in this case you didn't notice any difference between what you wanted and the undefined behavior you got.
The modifier for scanf to input a variable of type short is %hd. Hence you need to specify the correct modifier.
scanf("%d",&integer); // For integer type
scanf("%hd",&short_int); // For short type
Hence it doesnt work.
Depending upon numeric padding, endian-ness, and other such issues, you may be storing either the upper or lower part of the input value into choice; you are storing the rest of the input value into memory that may or may not be being used for anything else.