c - 来自数组的简单 Printf 循环

标签 c cygwin

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int
main(int argc,char **argv)
{
    int array[10];

    int count = sizeof(array) / sizeof(int);

    array[0] = 1;

    int index = 1;
    while (index < count)
    {
        array[index] = array[index - 1] * 2;
        index = index + 1;
    }

    while (index < count)
    { 
        printf("%d\n",array[index]);
        index = index + 1;
    }
    return 0;
}

我正在尝试循环 printf 语句以节省打字时间,这样我就不必每次想要打印出新结果时都输入整个内容。当我按上面的方式运行程序时,没有任何打印结果。

我的问题是:如何循环 printf 语句,这样我就不必编写

printf("%d\n", array[0]); 

对于每个新的 printf 命令等等,如果我的目标是打印出数组的所有 10 个值?

编辑:对于 future 的查看者,在打印语句之前将索引重新定义为 0。

最佳答案

第一个循环while (index < count)index == 10 时完成.

所以下一个循环while (index < count)永远不会输入,因为条件最初为假。

编写两个循环的更简洁的方法是:

for ( int index = 1; index < count; ++index )
{
    array[index] = array[index - 1] * 2;
}

for ( int index = 0; index < count; ++index )
{
    printf("%d\n", array[index]);
}

通过像这样将计数器变量的范围限定在循环中,可以防止程序中出现的那种错误。

关于c - 来自数组的简单 Printf 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25736397/

相关文章:

c - 结构指针操作

c - AMD64 指令指针中的奇怪行为

linux - 如何在 Windows 任务计划程序中运行 bash 脚本(驻留在远程服务器上)?

windows - 从命令行对十六进制数进行排序?

c - C 中的 fread 和 fwrite

C 线程和连接

c++ - C 与 C++ 中的枚举范围

java - 如何在java中编码以使用cygwin在Windows环境中运行内部使用rSync的unix shell脚本?

c++ - 安装了 Cygwin64 并且在 Eclipse 中无法在 <iostream> 中找到 Unresolved inclusion

python - 如何使用最新版本的 pip 下载或安装 Gitlib 作为独立库?