【发布时间】:2016-08-26 15:31:32
【问题描述】:
我正在阅读“Cracking the Coding Interview”一书,其中包含 C 语言中的几个算法示例。我想编写实现这些算法的程序并在我进行的过程中运行它们。
一种这样的算法是“Min and Max 1”(来自“Big O”一章):
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int x : array) {
if (x < min) min = x;
if (x > max) max = x;
}
我试图“围绕这个编写一个程序”,如下所示:
#include<stdio.h>
int array[5] = [1, 3, 2, 5, 4];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int main(void):
{
for (int x : array) {
if (x < min) min = x;
if (x > max) max = x;
}
printf("The minimum is %i", min)
printf("The maximum is %i", max)
}
但是,如果我尝试编译并运行它,我会得到error: expected identifier before numeric constant int array[5] = [1, 3, 2, 5, 4];。我将如何为这个示例输入数组正确实现这个算法?
【问题讨论】:
-
它是
int array[] = {1, 3, 2, 5, 4};(大小是根据您的数据自动计算的)。如果我没记错的话,这个for (int x : array) {是 C++11。 -
关于如何编写基本 C 语法的问题不是解决 SO 的好方法 - 我建议拿一本好书:stackoverflow.com/questions/562303/…