gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:52:09 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com