[英]how to print a list of numbers using printf in C++?
I am new learning C++ and I have basic questions and basic troubles :( 我是新学习C ++的人,我有基本的问题和基本的麻烦:(
I want to print a list of numbers that are coming from the next following while condition: 我想打印一个来自以下条件条件下的数字的列表:
int list=0;
while (list<100){
list=list+r;
}
I want to use printf instead of cout (because I still don´t know why with cout is not working). 我想使用printf而不是cout(因为我仍然不知道为什么使用cout无法正常工作)。
Can anyone help me to give me the analogous printf command to 谁能帮我给我类似的printf命令来
cout<<list<<"\t";
Thanks a lot!!! 非常感谢!!!
Here is a small sample program which counts up to 100 in increments of 10. 这是一个小示例程序,最多可以100递增10。
I use both std::cout
and printf
to display the value of list
in each increment. 我同时使用std::cout
和printf
在每个增量中显示list
的值。
Comments added to hopefully help aid you in learning 添加的注释有望帮助您学习
#include <iostream>
#include <cstdio>
int main()
{
int r = 10;
int list=0;
while (list < 100)
{
list += r; // this is the same as saying list = list + r, but is more succinct
std::cout << list << "\t"; // cout is in the std namespace, so you have to prefix with std::
printf("%d\n", list); // the printf format specified for int is "%d"
}
}
Output: 输出:
10 10 20 20 30 30 40 40 50 50 60 60 70 70 80 80 90 90 100 100
Please note that I didn't use using namespace std;
请注意,我没有using namespace std;
at the top to import cout
into the global namespace. 在顶部将cout
导入全局名称空间。 IMHO this is bad practice, so I typically will prefer std::cout
etc. 恕我直言,这是不好的做法,所以我通常会更喜欢std::cout
等。
printf
is a C function, not a C++ one, if you are learning C++ you should try to solve the problem with std::cout
, which is the usual way of printing. printf
是C函数,而不是C ++函数,如果您正在学习C ++,则应尝试使用std::cout
解决问题,这是通常的打印方式。
Anyway, printf
is pretty simple to use, it takes a first argument that is a string (a C string, so an array of char with the last char as a '\\0'
character) and as many parameters as you have format specifiers in your string (a format specifiers is a %
char followed by another char that the function what time the variable is going to be) 无论如何, printf
使用非常简单,它需要一个第一个参数,它是一个字符串(C字符串,所以一个char数组,最后一个char作为'\\0'
字符),并且包含与参数中一样多的参数您的字符串(格式说明符是%
char,后跟另一个char,该字符表示该函数将在什么时候变)
Examples: 例子:
int intvat;
char charvar;
float floatvar;
char* stringvar; // to print it the last char of stringvar must be \0
printf("this is an int: %d", intvar);
printf("this is a char: %c", charvar);
printf("this is a string: %s", stringvar);
printf("this is a float and an int: %f, %d", floatvar, intvar);
For more information about printf you can refer to the reference page here: http://www.cplusplus.com/reference/cstdio/printf/ 有关printf的更多信息,请参见以下参考页: http : //www.cplusplus.com/reference/cstdio/printf/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.