繁体   English   中英

打印位数而不是实际值

[英]Printing number of digits rather than actual value

我真的是 C 和编码的新手,如果这是一个简单的问题,我很抱歉。

我要做的就是输入一些数字,将它们相加,然后以两种不同的方式打印总和。 但是由于某种原因printf("%li", z); 代码行仅打印数字中的位数加1

有人可以向我解释为什么它会这样做吗? 为什么重要的是,我实际上并没有太在意让它工作,因为我只是在玩耍和练习。 谢谢!

我的代码如下:

#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);
}

错误就在这条线上

long z = printf("%li\n", x + y + y);

原因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); 您正在尝试编写x+y+y后跟\n (这是一个附加字符)。

printf在名为stdout的文件上打印出格式化字符串。 阅读本文了解更多详情。

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,文件)。 如果您想尝试小程序以查看它们是否成功,您可以使用调试器 ( gdb )。 但是为了理解这些函数的使用,你需要了解一些基本的东西,否则你会得到像scanf("%s %d", mystr, &myint)这样的神奇语法,你不知道为什么mystr不需要&myint需要。 因此,如果您没有这些基础知识,请在继续使用 IO 处理文件(stdout 和 stdin文件)之前学习它们。

#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); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM