我正在编写一个 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/