【问题标题】:Using a loop to run a program n amount of times使用循环运行程序 n 次
【发布时间】:2019-05-03 01:34:17
【问题描述】:

我是 C 编程语言的新手。我试图在 N 次以下运行代码(基于“输入迭代次数”的用户输入)。我正在尝试使用 for 循环(也尝试使用 while 循环)来执行此操作,但没有成功。

每当我运行下面的代码时,我的终端都会不断重复“输入两个浮点数:”。我必须关闭终端并重新打开它才能重试。这个问题与我的 for 循环有关吗?我将我的 for 循环解释为:“a=0;如果 a > 0;递增 a”。有没有办法可以为“if a > 0”设置限制,或者我应该使用 while 循环?如果用户输入“3”作为迭代次数,我希望程序会询问“输入两个浮点数”3 次(带有答案)。

        float sum (float m, float n){
        return m+n;}
        int main() {   
        float x, y;
        int a; 
        printf("Enter amount of iterations: ");
        scanf("%d", &a);
        for (int i; i < 0; i++) {
        printf("Enter two float numbers: ");
        scanf("%f %f", &x, &y);
        float su = sum(x,y);
        printf("%f and %f = ", x, y);
        printf("%f\n", su);}
        return 0;}

正确答案为便于阅读而格式化:

float sum(float m, float n)
{
    return m + n;
}

int main()
{
    float x, y;
    int a;
    printf("Enter amount of iterations: ");
    scanf("%d", &a);
    for (int i = 0; i < a; i++)
    {
        printf("Enter two float numbers: ");
        scanf("%f %f", &x, &y);
        float su = sum(x, y);
        printf("%f and %f = ", x, y);
        printf("%f\n", su);
    }
    return 0;
}

【问题讨论】:

  • 你有很奇怪的for循环:for (int a; a &gt; 0; a++),可能是这样写的for (int i = 0; i &lt; a; i++)
  • 请不要在 C 中使用 Pico 样式的缩进;它非常不正统,几乎无法阅读。此外,白色空间很便宜;用它!请使用 Allman(我喜欢的风格)或 1TBS(很多其他人喜欢它)——有关更多信息,请参阅 Wikipedia on Indentation Styles
  • 此外,printf 有一个缓冲区用于临时存储您的打印数据,直到它没有足够的填充,您可以在printf 之后使用fflush(stdout) 以避免缓冲您的输出。
  • 请注意,for 循环中的a 与前面代码中声明并由输入操作设置的a 不同且无关。 for循环中的a没有初始化;您无法确定循环将执行多少次。一个好的编译器应该警告你重新定义或隐藏a
  • 谢谢你,J.S!工作完美..第一天学习C。谢谢大家的指导。我将不再在 c 中使用 Pico 样式的缩进! :D

标签: c loops for-loop while-loop


【解决方案1】:

这应该更像您希望的那样:

#include <stdio.h>

static float sum(float m, float n)
{
    return m + n;
}

int main(void)
{
    float x, y;
    int a;
    printf("Enter amount of iterations: ");
    if (scanf("%d", &a) != 1)
    {
        fprintf(stderr, "Invalid input for iterations\n");
        return 1;
    }
    for (int i = 0; i < a; i++)
    {
        printf("Enter two float numbers: ");
        if (scanf("%f %f", &x, &y) != 2)
        {
            fprintf(stderr, "Failed to read to floating point numbers\n");
            return 1;
        }
        float su = sum(x, y);
        printf("%f and %f = ", x, y);
        printf("%f\n", su);
    }
    return 0;
}

请注意,它会检查输入操作是否成功,并在标准错误 (stderr) 上报告错误。代码使用标准的 C for 循环从 0 计数到一个极限 — 这是惯用的 C。你应该习惯使用它。

正如我在comment 中指出的,for 循环中的a 与前面在代码中声明并由输入操作设置的a 不同且无关。 for循环中的a没有初始化;您无法确定循环将执行多少次。一个好的编译器应该警告你重新定义或隐藏a

【讨论】:

    【解决方案2】:

    for (i = 0; i

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2016-12-12
      • 2014-06-06
      • 2019-02-19
      • 2023-03-24
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多