c - 计划在五年内返回五个城市的温度

标签 c

我正在编写一个 C 程序,旨在返回五个城市的温度,但我被卡住了。 我创建了一个 for 循环来遍历我创建的城市数组,另一个 for 循环来循环另一个温度数组。
这是代码:

// program to accept yearly temperature and display the max and minumum temp of five cities
#include <stdio.h>
int main() {
    //prompt user for yearly temperature of the five cities

    char cities[5][20];
    float temps[25];
    int i = 0;
    printf("Please enter the yearly temperature of the five cities\n");
    for (i; i <= 4; i++) {
      printf("Enter city %d \n", i + 1);
      scanf("%s", & cities[i]);

      for (i; i <= 4; i++) {
        printf("Enter temperatures for city %d\n", i + 1);

        for (i; i <= 24; i++) {
          printf("For year %d\n", i + 1);

          scanf("%f", & temps[i]);
          if (i == 5) {
            continue;
          }
        }
      }
    }
    return 0;
}

我遇到的问题是,当我运行代码时,如果 i = 5,它不会继续运行第三个循环,而是继续运行。 这是一个截图。 page1 page2

如您所见,代码一直运行到 25 点,然后才结束。 如果有人告诉我我做错了什么,那将会很有帮助。 谢谢。

最佳答案

您需要为每个循环声明一个变量。如果你想要三个不同的 i你应该写的变量:

// program to accept yearly temperature and display the max and minimum temp of five cities
#include <stdio.h>
int main() {
    //prompt user for yearly temperature of the five cities

    char cities[5][20];
    float temps[25];
    printf("Please enter the yearly temperature of the five cities\n");
    for (int i = 0; i <= 4; i++) {
      printf("Enter city %d \n", i + 1);
      scanf("%s", & cities[i]);

      for (int i = 0; i <= 4; i++) {
        printf("Enter temperatures for city %d\n", i + 1);

        for (int i = 0; i <= 24; i++) {
          printf("For year %d\n", i + 1);

          scanf("%f", & temps[i]);
          if (i == 5) {
            continue;
          }
        }
      }
    }
    return 0;
}

请注意,此代码仅在 C99 中有效。该语言的早期版本要求您在 for 循环中使用不同的变量名。

但是在上面提供的代码中,您的 continue 语句将无效,因为条件 i == 5是循环中的最后一条指令。如果你想终止循环你应该使用 break而不是 continue .在这种情况下,我将定义该循环的边界 i变量为 i < 5并完全摆脱 if 语句。
你应该了解 variable scoping在 C. 每个 i此处声明的变量是一个完全不同的变量,与重用相同 i 的代码相反再次变量导致程序提前终止。
我建议您始终为每个 for 循环声明一个变量,这样您的代码将始终更加清晰。

您提供的代码在算法上也是错误的。你想要的是重复五次五个城市的温度收集过程。在这种情况下,总迭代次数应为 25,因为 for 循环需要 O(n) iterations and a nested for loop requires O(n^k) iterations其中 k 是 for 嵌套循环的数量。每个循环重复出现 5 次所以 5^2 = 25 .

关于c - 计划在五年内返回五个城市的温度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48972238/

相关文章:

c - 在 C 中,为什么这个语句 - 'i = 5i' 编译并将 'i' 设置为零?

c++ - 英特尔编译器 (ICC) 无法自动矢量化内部循环(矩阵乘法)

c - printf 和 scanf 如何循环工作?为什么我在 scanf 中不需要\n?

c++ - 目前在 Ubuntu C/C++ 中如何将 IANA 时区名称转换为 UTC 偏移量

c - 从 uint32_t[16] 数组到 uint32_t 变量序列的 64 位副本

c - 代码片段中的错误

c++ - 指针指向指针的实际用途?

C位屏蔽AND运算问题

c - 如何系统地遵循递归?

c - 需要帮助改进一个小型 C 程序