【问题标题】:how to print a list of numbers using printf in C++?如何在 C++ 中使用 printf 打印数字列表?
【发布时间】:2017-03-04 16:13:55
【问题描述】:

我是新学C++,有基本的问题和基本的烦恼:(

我想打印一个来自下一个 while 条件的数字列表:

int list=0;
while (list<100){
    list=list+r;
}

我想使用 printf 而不是 cout(因为我仍然不知道为什么 cout 不起作用)。

谁能帮我给我类似的printf命令

cout<<list<<"\t";

非常感谢!!!

【问题讨论】:

  • 你上过谷歌吗?
  • "(因为我仍然不知道为什么 cout 不起作用" 找出答案是个好主意。
  • printf("%d\t", list); printf 使用起来不如 cout 直观;你会更好地找出造成你麻烦的原因,你在使用std::cout (std namespace) 吗?您是否正在刷新输出缓冲区:std::cout&lt;&lt;list&lt;&lt;"\t" &lt;&lt; std::endl;
  • “因为我仍然不知道为什么 cout 不起作用” 它是如何不起作用的。如果您详细说明这一点,我们可能会帮助您解决可能的问题。
  • 代码中的“r”是什么?

标签: c++ while-loop printf cout


【解决方案1】:

这是一个以 10 为增量最多计数 100 的小示例程序。

我同时使用std::coutprintf 来显示list 在每个增量中的值。

添加的评论希望能帮助您学习

#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"
    }
}

输出:

10    10
20    20
30    30
40    40
50    50
60    60
70    70
80    80
90    90
100   100

请注意,我没有在顶部使用using namespace std;cout 导入全局命名空间。恕我直言,这是不好的做法,所以我通常更喜欢std::cout 等。

【讨论】:

  • 您似乎没有包含 any 标头来获取 printf() 的声明。
  • @NeilButterworth 它可以从&lt;iostream&gt; 间接获得。 Working example here
  • 你不能依赖这些东西 - 标准说任何标题可能包含另一个标题,但它没有说任何标题必须 包括另一个。如果您使用标准库中的函数,则应始终包含标准声明的标头。
  • @SteveLorimer 非常感谢您的回答,这真的很治愈。但是,我仍然有疑问,如果列表中的数字是带小数的数字,我将如何更改该代码?我试图将 int 更改为 double 但它不起作用。有什么建议么?再次感谢
  • @angelavtc 你真的应该问另一个问题,或者更新你的问题以反映新的要求。 SO 不是论坛,而是问答网站。但是,在这种情况下,std::cout 将输出十进制而不做任何更改。对于printf,您想使用%f%g。请阅读更多here
【解决方案2】:

printf 是 C 函数,不是 C++ 函数,如果你正在学习 C++,请尝试使用 std::cout 解决问题,这是通常的打印方式。

无论如何,printf 使用起来非常简单,它的第一个参数是一个字符串(一个 C 字符串,因此是一个 char 数组,最后一个 char 是一个 '\0' 字符)和与你一样多的参数在您的字符串中有格式说明符(格式说明符是一个 % 字符,后跟另一个字符,该函数表示该函数的时间)

例子:

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

有关 printf 的更多信息,您可以参考此处的参考页面:http://www.cplusplus.com/reference/cstdio/printf/

【讨论】:

  • 我不明白。 C++语言中包含printf,所以我相信printf是一个C++函数。请引用您的参考资料,说明 printf 不是 C++ 函数。
  • 与来自cstdio 的任何东西一样,printf 是一个 C 函数,它已包含在 C++ 标准库中以实现兼容性(主要目标之一是每个 C 代码都应该是合法的C++ 代码,或者尽可能少地修改)。一个引用是 stackoverflow.com/questions/2872543/printf-vs-cout-in-c ,另一个引用是答案中的同一站点,cplusplus.com/reference/clibrary 这里谈到了 C++ 中的所有 C 头文件,其中有 cstdio,其中定义了 printf
  • @bracco23 非常感谢您的回答,这真的很有用:)
猜你喜欢
  • 2023-02-09
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多