【发布时间】:2021-06-10 10:38:09
【问题描述】:
我正在尝试制作一个程序,该程序接受一系列数字并打印最大的数字。逻辑很简单——将序列作为一个数组,使用插入排序的第一步来检查最大的数字。当我运行程序时,它会一直运行到“逐个输入数字”。我输入一个数字并按回车键,一秒钟内没有任何反应,程序自行终止。我在第一个 for 循环中遗漏了什么?
#include <stdio.h>
void largest_number(int ar[], int size);
int main()
{
int ar[100], index, size;
printf("Enter total numbers = ");
scanf("%d", &size);
printf("Enter the numbers one by one\n");
for (index = 0; index < size; index++)
scanf("%d", ar[index]);
largest_number(ar, size);
}
void largest_number(int ar[], int ar_size)
{
int index, location = 0;
for (index = 1; index < ar_size; index++)
if (ar[index] > ar[location])
location = index + 1;
printf("The largest number is %d", ar[location]);
}
【问题讨论】:
-
scanf("%d", ar[index]);,需要传递ar[index]的地址 -
欢迎来到 SO。您的编译器应该警告
scanf中的类型不匹配。如果它没有警告您,您需要调高诊断级别。对于 GCC,您可以通过选项-Wall -Wextra执行此操作 -
顺便说一句,为什么
location = index + 1;?+ 1是干什么用的? -
我刚刚了解了 scanf 部分。我正在使用vscode,它没有给出任何错误。顺便谢谢!以及如何在 vscode 中调高诊断级别?
-
我更改了
location = index +1,这是错误的。不需要增量