c++ - 如何在每 x 步*仅*显示值

标签 c++ loops iteration counter

我正在尝试完成一个计算 2 的自然对数的程序,该程序基于要使用的所需项数以及每 x 步后要显示的值的数量。例如,如果用户输入 6 个术语,每 2 步显示一次,它就会有这个输出;

0.5000000000

0.5833333333

0.6166666667

代替:

1.0000000000

0.5000000000

0.8333333333

0.5833333333

0.7833333333

0.6166666667

对于我正在尝试做的事情,此循环无法正常工作,我正试图找出要对其进行哪些调整才能正常工作。任何帮助表示赞赏。

    for(double x = 1; x <= numofterms; x += 1){

    logarithm += denominator * 1 / x;
    denominator = -denominator;

    int printCounter = 0;
    for(int i=1; i<=numofterms; i++) {
    printCounter++;
      if(printCounter >= displaycount) {
         cout << setprecision(10) << showpoint << logarithm << endl;
         printCounter = 0;
 }

最佳答案

您正在使用 printCounter >= displaycount这是错误的

让我们说 printCounter是 100 和 displaycount是 20 所以你应该得到 6 行,但是在 printCounter 之后达到 20 时,它会显示每一行,所以你得到 81 行。

所以最好使用printCounter % displaycount == 0这只会显示 0,20,40,60,80,100 的行printCounter 的值

关于c++ - 如何在每 x 步*仅*显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25194143/

相关文章:

c++ - 使用什么代替静态变量

Java - 遍历 ArrayList 行(列)?

c++ - 在运行时反复使用和对象的最佳实践是什么

c++ - 如何解决 Cppcheck 中的问题 ID "toomanyconfigs"和 "missingInclude:"

循环内的 JavaScript 闭包 – 简单的实际示例

Python 分类命令

javascript - 在 Javascript 中,如何同时对两个 seqs 的元素执行一个函数?

python - 如何比使用两个for循环更快地对图像的每个像素执行操作?

c++ - 将随机数与 vector 大小进行比较时出错

python - 仅计数迭代器附加最终计数值