for循环:在一个循环中进行增量和访问 [英] for loop: make increment and accessing in one loop

查看:69
本文介绍了for循环:在一个循环中进行增量和访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么这会给我带来垃圾:

I do not know why this is giving me garbage:

#include <stdio.h>
int main(){
int a[10];
for(
    int i =0;
    i++<10;
    a[i-1]=i
   )
 {
  printf("%i:%i\n", i-1, a[i-1]);
 }
}

哪个给我:

0:1676584240
1:32609
2:0
3:0
4:-1577938528
5:21992
6:-1577938864
7:21992
8:2114427248
9:32766

索引看起来正确,甚至循环内的分配也正确(例如 printf(%i \ n",a [0])给出 1 在循环之后是正确的).但是在for循环的主体内部,printf尽管具有正确的索引,但给出了错误的值(有些垃圾).为什么会这样?

The indices looks correct, and even the assignment inside the loop, is correct (e.g. printf("%i\n",a[0]) gives 1 which is correct, after loop). But inside the body of for loop, the printf, despite having correct indices, gives wrong values (some garbage). Why is that?

编辑,对 ...&&(a [i] = i),我尝试使用其他语句来做到这一点:

EDIT, after some answers with ... && (a[i]=i), I have tried to do that with other statements:

for(
 int i = 0;
 i<10 && (a[i]=i);
 (i++) && printf("%i\n", a[i])
 );

但这不会打印任何内容,只是发出警告:

But that does not print anything, just gives warning:

warning: value computed is not used [-Wunused-value]
   i++ && printf("%i\n",a[i])

为什么?当我可以使真实"(a [i] = i)的语句,为什么我不能使"true"?(i ++)的陈述?

Why? when I can make "true" statement of (a[i]=i), why cannot I make "true" statment of (i++)?

推荐答案

在做

for(
    int i =0;
    i++<10;
    a[i-1]=i
   )
 {
  printf("%i:%i\n", i-1, a[i-1]);
 }

您在之后设置条目,然后打印它们,因为 a [i-1] = i 正文之后>对于,因此您将打印未初始化的数组条目

you set the entries after you print them because a[i-1]=i is executed after the body of the for, so you print non initialized array entries

您的代码也很复杂",因为您在 for 的测试部分中增加 i 的时间太早,这是一种(可能)想要做的标准"方式是:

your code is also 'complicated' because you increase i too earlier in the test part of for, a 'standard' way to do what you (probably) want is :

for(int i = 0; i < sizeof(a)/sizeof(*a); ++i) {
  a[i]=i+1;
  printf("%i:%i\n", i, a[i]);
}

如果您真的不想体内有 a [i] = i + 1; ,可以这样做:

if you really want to not have a[i]=i+1; in the body you can do that :

for(int i = 0; (i < sizeof(a)/sizeof(*a)) && (a[i]=i+1); ++i) {
  printf("%i:%i\n", i, a[i]);
}

为了避免在编译时出现警告,请执行 ...&&((a [i] = i + 1)!= 0);

to avoid a warning when compiling do ... && ((a[i]=i+1) != 0);

请注意(a [i] = i + 1)并非错误,因为值至少为1,如果您想执行 a [i] = i 使用的测试可以是(i< sizeof(a)/sizeof(* a))&&(a [i] = i,1) i 为0

note (a[i]=i+1) is not false because values at least 1, in case you wanted to do a[i]=i the test to use can be (i < sizeof(a)/sizeof(*a)) && (a[i]=i, 1) to not be false when i is 0

但是这不利于读取代码^^

but that does not help to read the code ^^

这篇关于for循环:在一个循环中进行增量和访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆