【问题标题】:Why for loop does not run by other than int variables? [closed]为什么 for 循环不能由 int 变量以外的其他变量运行? [关闭]
【发布时间】:2013-01-27 05:54:15
【问题描述】:

为什么 for 循环不能由非 int 变量运行?我试图通过使用浮点变量来运行 for 循环,但它不能由除 int 类型之外的任何其他变量运行?

【问题讨论】:

  • 显示一些代码,否则您的问题将被关闭。
  • 一些代码总是有用的。
  • 顺便说一句,一个工作示例:int main(){ float i = 0.0; for(i=0.0; i<=3; i+=0.5){ printf("%.3f\n",i); } return 0; }
  • 这篇文章回答了您的问题以及更多其他问题。在提问之前您是否搜索过 SO 网站? What is the full "for" loop syntax in C (and others in case they are compatible)?

标签: c for-loop


【解决方案1】:

您可以使用带有整数变量、浮点变量甚至完全没有变量的 for 循环。

int i;
for(i = 0; i < 10; i++) continue;

float f;
for(f = 0.0; f < 5; f += 0.5) continue;

for(;;) break;

但是请参阅What Every Computer Scientist Should Know About Float-Point Arithmetic,了解为什么在使用示例 2 之前应该三思而后行。

【讨论】:

    【解决方案2】:

    你应该可以通过使用 STEP 命令来做到这一点

    float X = 0;
    //
    //increase in steps of 1 x 1 thousandth
    for (X = 1; X <= 100; X += 0.001) {
      // DISPLAY YOUR RESULT  maybe using: Math.Round(X, 3)
    }
    

    【讨论】:

    • 我只是在 VB 中的一个网页上尝试过,然后转换它并将该行留在
    • 这个问题被标记为C。你为什么在你的答案中使用VB?
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2014-05-01
    • 1970-01-01
    相关资源
    最近更新 更多