Im really new to C and coding in general so sorry if this is a simple problem.
All I'm trying to do is input some numbers, get them to be added up, and then print the sum in two different ways. However for some reason the printf("%li", z);
line of code is only printing the amount of digits in the number plus 1
.
Could someone explain to me why exactly it is doing this, please? The why what's important, I'm not actually too bothered about getting it to work since I'm just playing around and practising. Thanks!
My code is as follows:
#include <cs50.h>
#include <stdio.h>
int main(void) {
long x = get_long("what is x: ");
long y = get_long("what is y: ");
long z = printf("%li\n", x + y + y);
printf("%li", z);
}
The mistake is in the line
long z = printf("%li\n", x + y + y);
The reason printf("%li", z);
prints the number of the digits in the number plus one is that printf
is a function that returns the number of characters written on the output stream (stdout -- the console -- in your case) and here printf("%li\n", x + y + y);
you're trying to write x+y+y
followed by \n
(which is an additional character).
printf
prints out a formatted string on a file called stdout
. Read this for more details.
Please, if you are new to the C language, I advise against trying to learn more "advanced" stuff like printf
or scanf
(and *printf
or *scanf
function family) without having the proper basics (variables, pointers, dynamic memory allocation, files). If you want to try out small programs to see if they succeed you can use a debugger ( gdb
). But in order to understand the use of those functions you need to know some basic things, or you will end up with magic syntax like scanf("%s %d", mystr, &myint)
and you wouldn't know why mystr
does not need the &
whereas myint
does. So, please, if you don't have these basics, learn them before going on with IO on files (stdout and stdin are files).
#include <cs50.h> #include <stdio.h> int main (void) { long x = get_long("what is x: "); long y = get_long("what is y: "); long z = x + y + y; printf("%li", z); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.