Calculating percentages in C - c

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.

Related

Double, Integer, Long double

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".

What is the correct specifier for char, double and float?

#include <stdio.h>
int main()
{
int i;
long int l;
long long int ll;
char a;
float F;
double D;
scanf("%i%li%lli%c%f%lf",&i,&l,&ll,&a,&F,&D);
printf("%i\n%li\n%lli\n%c\n%f\n%lf\n",i,l,ll,a,F,D);
return 0;
}
When I tried to print the value of a,F and D in the above program, it is printing 'h' for 'char' and 0.000000 and 0.000000 for float and double every time .
input: 3
444
12345678912345
a
334.23
14049.30493
output:3
444
12345678912345
0.000000
-0.000000
printf
There's no way to pass a char or a float to printf. They'll be promoted to int and double respectively in the processing of being passed.
When you pass a double, you can use %f or %lf (the latter was added in C99 though, so some older compilers don't support it).
If you want your int printed as a character, you can use the %c conversion. If you want it printed as a number, you can use the %d or %i conversion.
scanf
For scanf you don't want to pass any of the above--you want to pass a pointer to a (char | float | double).
As for the conversion to use, for a pointer to char you can use either %c or %s.
%s reads a "word"--it skips white-space characters, then reads a group of non-white-space characters.
%c does more like "raw" reading--for example, if you specify %15c it reads the next 15 characters, regardless of whether they're white-space or not.
With both %c and %s, you always want to pass a with (like %15s instead of just %s) to assure that the user can't enter too much data and overflow the buffer you've provide. scanf("%s", whatever); is pretty much equivalent to using gets.
With scanf, you pass %f to read a float and %lf to read a double.
Use %c for char .
Note - You should check return of scanf .
Demo
When you read your input, the character you read is the white-space between 12345678912345 and a. That means that the next format, the floating point, will try to read the letter a as a floating pointer value which will not work, and the scanf function will return without being able to correctly read and parse all input, leading to your output not matching the input. Many standard and system function returns a value saying if it succeeded or failed, the same with the scanf function, and if it doesn't fail completely it will return the number of successfully scanned and parsed items, which would be less than expected in your case.
The scanf reference in one of my comments will tell you that most formats skip leading white-space, but "%c" does not. If you want to skip leading space before attempting to parse a character, you need to tell scanf to do that, by inserting an actual space in the format string, like this:
scanf("%i%li%lli %c%f%lf",&i,&l,&ll,&a,&F,&D);
// ^
// Notice space here

Need some assistance with understanding char->ASCII and some basics

I had a project to write this program that reads a character, integer and a floating number. It also had to convert the character in to its ASCII integer. I vaguely understand most of it except the code regarding the ASCII number. I created most of it on my own but when it came to converting the character I had a buddy help me, but he is not the best at explaining this.
Any explanation would be very helpful, thank you. I did this all by trial and error for... probably far too long :P
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char c;
int i;
float f;
printf ("Please enter a character: ");
scanf ("%c", &c);
printf ("Please enter an integer: ");
scanf ("%d", &i);
printf ("Please enter a floating point number: ");
scanf ("%f", &f);
printf ("\n");
printf ("The character you entered is: %c which is %d in integer-specification\n", c,c);
printf ("The integer you entered is: %d.\n", i);
printf ("The floating-point number you entered is: %f.\n", f);
return 0;
}
It will be helpful to have a reference documentation of printf handy.
When the format specifier is %c, printf expects an int. A char works since it is promoted to an int.
When the format specifier is %d, printf expects an int. A char works since it is promoted to an int.
For the first case, printf prints the character corresponding to the value of the int.
For the second case, printf just prints the number.
Essentially a char is just an integer with a range from 0 to 255, the only thing that makes it a 'character' is that we have assigned characters to be represented by certain numbers.
What's going on in the printf() is that first you tell it that you're going to pass a char and would it please just output that byte to be displayed, then you say that you want it to convert an integer to a string and output that.
What it boils down to is that the ASCII code is the character.
Note: for reasons that are not important at the moment when being passed into a vararg function like printf() chars and shorts are promoted to ints.
Here is my attempt at explaining this.
Everything in a program memory is stored as sequences of 0s and 1s (binary numbers). You are probably familiar with bits and bytes, but just in case: a binary digit (0 or 1) is a bit. A sequence of 8 bits is a byte. Characters, such as 'A', 'b', '1', etc. have to be stored as numbers in memory. There are different ways to map a character to a number: EBCDIC (very rare these days, was used on large mainframes in the old days), UTF-8, UTF-16, UTF-32 (types of Unicode), ASCII. These mappings are called character encodings, and ASCII is the simplest of those commonly used.
So, when you enter a character, it gets stored in the variable c as an integer number encoded using ASCII. The content of memory location corresponding to the variable can be thus viewed both as a character and an integer.
When using the printf() function you can request the same variable to be printed using different possible representations. In this case, since c is a character variable and can be represented as a character or a number, you can use the different format specifiers, %c and %d, to have it printed as character and integer, respectively.
The 1st of the printf() calls above takes 3 arguments. The first argument is a string that is printed out, with things that start with % being used to interpret the remaining arguments. %c corresponds to the 2nd argument, %d to the 3rd. %c says: "treat the 2nd argument as character and print it out." %s says: "treat the 3rd argument as integer and print it out."
The other 2 printf() calls in your code take only 2 arguments. The 1st argument, the string, contains only one thing starting with % (format specifier), so we only need 1 additional argument to be interpreted using the format specifier.
Hope this is helpful.
the Man ascii will make you understand

Double and Float format displaying different results

I thought that the difference between double and float were the precision of the decimals. However, I am getting strange results with using double and float and they are no where close to one another.
The first segment of code is used with the float format producing the correct results:
#include <stdio.h>
#define ABSOLUTE_VALUE(number) ( ((number) < 0) ? -(number) : (number) )
int main (void)
{
float number, absNumber;
printf ("What number do you want to check the absolute value for? : ");
scanf ("%f", &number);
absNumber = ABSOLUTE_VALUE(number);
printf ("The absolute value of %.2f is %.2f\n", number, absNumber);
return 0;
}
Output:
What number do you want to check the absolute value for? : -3
The absolute value of -3.00 is 3.00
The second segment of code is used with the double format producing incorrect results:
#include <stdio.h>
#define ABSOLUTE_VALUE(number) ( ((number) < 0) ? -(number) : (number) )
int main (void)
{
double number, absNumber;
printf ("What number do you want to check the absolute value for? : ");
scanf ("%d", &number);
absNumber = ABSOLUTE_VALUE(number);
printf ("The absolute value of %.2d is %.2d\n", number, absNumber);
return 0;
}
Output:
What number do you want to check the absolute value for? : -3
The absolute value of -03 is 2147344384
In the second example, %d is used for integers. (d isn't short for double, but for decimal)
scanf ("%d", &number);
should be
scanf ("%lf", &number);
The printf is incorrect too, as %fis used for double
printf ("The absolute value of %.2d is %.2d\n", number, absNumber);
Instead, this should be:
printf ("The absolute value of %.2f is %.2f\n", number, absNumber);
Notice that the format specifier for double is different for scanf and printf, this C FAQ article has some good explanations.
Your last printf format string is wrong. Should be.
printf ("The absolute value of %.2f is %.2f\n", number, absNumber);
and if you enable all compiler warnings (e.g. compile with gcc -Wall -g) you'll have a warning about that. Always enable all warnings in the compiler.
Your scanf are also wrong, should be scanf("%lf", &number); and with all warnings the compiler would have warned you.
BTW, scanf returns the "number of successfully matched items" and you should test its result.
You really need to carefully read the documentation of printf(3) and of scanf(3). (In a linux terminal, you could type man 3 printf to get it).
Notice that arguments are converted to double and the conversion specifier for double-s is %f in printf and %lf in scanf
And you should learn how to use a debugger (like gdb).
In your second program, you have used %d format specifier for double which is wrong. And that's why you are getting error. You should use %lf (long float or better called 'double') for printing it.
For other format specifier,
I think this might help you
a link
You can also search different format specifiers on google by typing 'format specifiers'.
Make 2 changes for using double data-type in c :
use %lf in scanf
use %f in printf
//remember : %d is for int
%f is for float
%c is for char
If you read the manual, "%d" is for integers. You need "%lf" instead.
Ditto with the printf

about C and eclipse - scanf

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

Resources