I'm still a beginner at C, so I'm finding difficulty in understanding "%d! = %ld".
I know that %d and %ld are respectively used for an integer and long, so "! =" is confusing me.
#include<stdio.h>
long factorial(int);
int main() {
int n;
long f;
printf("Enter an non-negative integer: ");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else {
f = factorial(n);
printf("%d! = %ld\n", n, f); //what does this mean?
}
return 0; }
long factorial(int n) {
if (n == 0)
return 1;
else
return(n * factorial(n-1)); }
This will print:
%d, i.e. the decimal value of int n
! =, i.e. the literal character sequence
%ld, i.e. the decimal value of long f
%d and %ld are the formatting placeholders for int and long int in printf. The exclamation point is just the factorial symbol, as mentioned in the comment.
printf() allows you to print a string with variables inside of it. Let's say you have a variable i, containing an integer, 7.
printf("My variable is %d", i);
Will print
My variable is 7
to the console! That's because %d is how you tell printf(), "Hey, put an integer variable here!". The integer is then supplied as the next argument to the function. In your case, %d represents the integer n, and %ld represents the long integer f. Since f might be really big, we make it a long, which means more bytes are allocated to it internally on your computer. So for example, if we wanted to get the factorial of 5 and print it, we might do the following:
printf("Factorial of %d equals %ld\n", 5, factorial(5))
// this will print "Factorial of 5 is 120" then a newline
Oh, and \n just means print a newline afterwords!
printf("%d! = %ld\n", n, f); //what does this mean?
%d - print an integer as a signed decimal number.
l - specifies that the argument is a long int or unsigned long int as appropriate. %ld then prints a long int or unsigned long int
The printed text will become something like
n! = f
(factorial notation n!)
Related
I have compiled this code and it works just fine up to value 4 then it starts returning character instead of integer. I am talking about first equation => x= num*2; Here when I enter num value as 5 the output returns a.
#include <stdio.h>
int main(void)
{
int num;
int x; This right here is an integer still it returns a character
char s[10] = "helloworld";
char f[10];
scanf("%d", &num); //
//printf("%d\n", num);
x = num * 2 ;
printf("%x\n", x);
scanf("%c", &f[10]);
if(s[10] = f[10]){
printf("helloworld");
}
}
please tell me if there is a mistake I am a newbie to coding.
As I see you are learning C language, and after reading your explanation, I feel that you want to print the integer value of variable x.
Kindly replace %x with %d in the print statement of variable x,
and you will be successfully able to print the value.
#include <stdio.h>
int main(void)
{
int num;
int x; // This right here is an integer still it returns a character
char s[10] = "helloworld";
char f[10];
scanf("%d", &num);
x = num * 2 ;
printf("%d\n", x); // %d for integer and %x for hexadecimal values
scanf("%c", &f[10]);
if(s[10] = f[10]){
printf("helloworld");
}
return 0;
}
Finally, do read more about format specifiers in scanf and
printf statements.
using a simple code:
#include <stdio.h>
int main(int argc, int **argv)
{
int A, B, C, D, E, F;
printf ("input 1 : ");
scanf ("%d", &A);
printf ("input 2 : ");
scanf ("%d", &B);
C = A + B;
D = A - B;
E = A * B;
F = A / B;
printf ("sum : %d\n", C);
printf ("difference : %d\n", D);
printf ("product : %d\n", E);
printf ("quotient : %d\n", F);
return 0;
}
My question is as such, in the first scanf [p.s I know I can use other input methods its for a project] if you input a float/double number such as 1.3 or 20.5
the sum and difference are quite random for me,anyone can explain to me why the results are what they are?
Continuing from the comments, you must always validate all input (especially user input). All input functions provide a return. The scanf family returns the match count, the number of successful conversions processed based on the number of format specifiers in the format string. You use that to validate your input. E.g., at minimum:
#include <stdio.h>
int main(int argc, int **argv)
{
int A, B, C, D, E, F;
printf ("input 1 : ");
if (scanf ("%d", &A) != 1) {
fprintf (stderr, "error: invalid input - A.\n");
return 1;
}
printf ("input 2 : ");
if (scanf ("%d", &B) != 1 || B == 0) {
fprintf (stderr, "error: invalid input - B.\n");
return 1;
}
C = A + B;
D = A - B;
E = A * B;
F = A / B;
printf ("sum : %d\n", C);
printf ("difference : %d\n", D);
printf ("product : %d\n", E);
printf ("quotient : %d\n", F);
return 0;
}
note: your "quotient" will always be the result of integer division and truncated accordingly.
The first scanf(), if the input has a decimal point will stop at the decimal point and leave it to be read on the next operation. For input of 1.3, this means A will get the value 1, and the .3 will remain in the input stream to be read. This is because of the %d format - which tells scanf() to expect an integral value, and to stop on any characters that do appear in any representation of an integral value. A decimal point is one such character that is not used in the representation of an integral value.
The next operation (scanf("%d", &B)) immediately encounters the decimal point and returns, without changing B.
Since B is not initialised at all (before, during, or after the scanf("%d", &B)) in the program, any subsequent attempt to access its value gives undefined behaviour. Among other things, this can mean the value of B is indeterminate. From what you describe, for your setup, that results in "random" input.
If you're expecting to read input that looks like floating point values (e.g. that contains a decimal point) either read as floating point (e.g. %f format, and variables of a floating point type) or read a whole line (e.g. using fgets()) and check the contents of the line BEFORE trying to read integral values from it.
If you insist on using scanf(), check its return value. On the second call of scanf() in your scenario, scanf() will return 0 rather than 1 (since it has read no values, rather than the one value the format string specified). Which is an indication that something has gone wrong reading the input.
I been having issues having my C code work. I have 1 warning, which states Warning: too many arguments for format. I am a beginner in C so I haven't encountered this issue yet. Any ideas on how to fix it and I cannot use conditions as I am in the beginning segment of my course learning from the start. I just need to know what I did wrong so I can fix the issue. Here's the code below:
#include <stdio.h>
int main() {
float firstNumber, secondNumber, thirdNumber;
float fourthNumber, fifthNumber;
float sumAverage1 = (firstNumber+secondNumber+thirdNumber);
float sumAverage2 = (fourthNumber+fifthNumber);
long a = 1000000000;
long b = 1250000000;
long c = 1500000000;
long d = 1750000000;
long e = 2000000000;
printf("A is %li\n", a);
printf("B is %li\n", b);
printf("C is %li\n", c);
printf("D is %li\n", d);
printf("E is %li\n", e);
printf("Enter 5 Random numbers and guess what the total will be summed up when program runs.\n");
printf("You cannot enter a decimal integer and enter numbers below 100.\n");
scanf("%f", &firstNumber);
scanf("%f",&secondNumber);
scanf("%f",&thirdNumber);
scanf("%f",&fourthNumber);
scanf("%f",&fifthNumber);
printf("Your numbers average out to:\n", sumAverage1+sumAverage2/5);
system("pause");
return 0;
}
The line:
printf("Your numbers average out to:\n", sumAverage1+sumAverage2/5);
Has an argument but no format specifier. Also, that expression is unparenthesized; the division has higher precedence than the addition, so what you're calculating is sumAverage1+(sumAverage2/5), which is integer division, which is probably not what you want.
What you probably want is:
printf("Your numbers average out to: %f\n", (double)(sumAverage1+sumAverage2)/5.0);
Here this will solve all your problem.
#include <stdio.h>
#include <stdlib.h>
int main() {
float firstNumber, secondNumber, thirdNumber,sumAverage1;
float fourthNumber, fifthNumber,sumAverage2;
long a = 1000000000;
long b = 1250000000;
long c = 1500000000;
long d = 1750000000;
long e = 2000000000;
printf("Enter 5 Random numbers and guess what the total will be summed up when program runs.\n");
printf("You cannot enter a decimal integer and enter numbers below 100.\n");
scanf("%f",&firstNumber);
scanf("%f",&secondNumber);
scanf("%f",&thirdNumber);
scanf("%f",&fourthNumber);
scanf("%f",&fifthNumber);
sumAverage1 = (firstNumber+secondNumber+thirdNumber);
sumAverage2 = (fourthNumber+fifthNumber);
printf("A is %li\n", a);
printf("B is %li\n", b);
printf("C is %li\n", c);
printf("D is %li\n", d);
printf("E is %li\n", e);
printf("Your numbers average out to:%f\n", (sumAverage1+sumAverage2)/5);
system("pause");
return 0;
}
I ran this on my Visual Studio and it works just fine. Hope it Solves your Problem.
You need to change the printf format specifier, but your scanf does not capture the extra dangling newline. You need to either clear the buffer, fflush(stdin) after each scanf() or you need an extra scanf("%c") to get rid of the newline character.
See scanf() leaves the new line char in buffer?
Let me start by saying that I am brand new to programming. I am a math major and I don't know very much about the computer programming world. That said, my assignment wants me to enter an integer and print it out as the corresponding ASCII character, decimal, float. I am ok going from a character to the corresponding integer, but the reverse has me puzzled. Please help!
#include <stdio.h>
int main (void)
{
char E = 'E';
char e = 'e';
char D = 'D';
char d = 'd';
int m;
printf("\nPlease enter an integer : ");
scanf("%d", &m);
printf("\nThe number as a character is : %c", E, e, D, d);
return 0;
} // main
This is what I have so far, but I know it's wrong.
I am not exactly sure what you want to achieve.
printf will treat a parameter as a type you want using % format specifier.
So if you have entered some value which is interpreted as signed decimal integer you can print it treating as a different type with the printf function.
If you want your m variable being printed as character do:
printf("The number as a character is %c", m);
If you want to display it as a float, use %f.
Here is some reference:
http://www.cplusplus.com/reference/cstdio/printf/
You're probably looking at the printf formats
#include <stdio.h>
int main (void)
{
int m;
printf("Please enter an integer : ");
scanf("%d", &m);
printf("The number as a character is : '%c' %02X %o %d %f", m, m, m, m, (float) m);
return 0;
}
I am trying to understand sscanf behaviour for that I have executed below two program.
void main()
{
char *a = "225.311";
int x = 0, y = 0;
sscanf(a, "%d.3%d", &x, &y);
printf("x is %d, y is %d\n", x, y);
}
output is
x is 255, y is 11
Below program is not working as per my expectation.
void main()
{
char *a = "225.311";
int x = 0, y = 0;
sscanf(a, "%d5.3%d", &x, &y);
printf("x is %d, y is %d\n", x, y);
}
I am expecting 25,11, but the output is
x is 255, y is 0
I am expecting sscanf behaviour should exact same as sprintf in reverse manner. But its not working in my second program. If the format specifed is %d5.3%d, then it has to consider 5 as delimeter. But its not considering and reading all digits for x, and then dot is not matching with 5.3%d so it quits there.
Can somebody please explain this.
That's because the %d conversion specifier means sscanf will keep reading from the buffer pointed to by a till it encounters a non-numeric character in the buffer. This means that %d will consume up till 225 in the string literal "225.311" in your second example.
If the format specifed is %d5.3%d, then it has to consider 5 as
delimeter.
No, that's not true. 5 in the format string means sscanf will match it exactly (after reading an int) in the buffer it reads from. If it fails to match it, then sscanf will return and the value of y is left unchanged. You can check for this by storing the result of sscanf. The return value is equal to the number of input items successfully matched and assigned.
char *a = "225.311";
int x = 0, y = 0;
int retval = sscanf(a, "%d5.3%d", &x, &y);
printf("%d\n", retval); // prints 1
However, note that if the sequence of numeric characters in the buffer is too long to fit into an int, then the behaviour is undefined because of signed integer overflow.
Suggest using a different format and checking the results of sscanf(). Also to distinguish fractions like "0.001" and "0.1", note positions.
const char *a = "225.0311";
int ipart = 0;
unsigned fractionpart;
int n1, n2;
if (sscanf(a, "%d.%n%u%n", &ipart, &n1, &fractionpart, &n2) != 2) {
Handle_BadInput();
}
printf("ipart is %d, fractionpart is %0*u\n", ipart, n2 - n1, fractionpart);
// ipart is 225, fractionpart is 0311
As #ajay discusses, "%d5.3%d" looks for an int, then "5.3" then another int.