在C语言中,我只允许使用stdio.h,不允许使用数组。
问题是:我需要编写函数“void maxlegnth()”
输入整数只要是正数,如果输入负数,输入部分就会停止。
我需要找出相同数字的最长序列,以及它发生的次数。例如:
输入:
19 19 97 97 97 97 681 681 681 681 97 36 36 36 97 97 97 97 36 -19
输出:
maximum length - 4
occurred - 3
我一直在思考这个问题,但我不知道该怎么解决:
void MaxLength()
{
int num1, temp, currentmax = 0, countmax = 0, globalmax = 0;
printf("Please enter positive integers: ");
scanf_s("%d", &num1);
temp = num1;
if (num1 > 0)
currentmax++;
while (num1 > 0)
{
scanf_s("%d", &num1);
if (num1 < 0)
{
//currentmax--;
break;
}
if (num1 == temp)
{
currentmax++;
temp = num1;
if (currentmax > globalmax)
globalmax = currentmax;
}
else
{
if (currentmax > globalmax)
{
globalmax = currentmax;
countmax = 1;
currentmax = 1;
temp = num1;
}
if (currentmax < globalmax)
{
currentmax = 1;
temp = num1;
}
if (currentmax == globalmax)
countmax++;
}
}
printf("\ncurrent %d\n", currentmax);
printf("\nglobal %d\n", globalmax);
printf("\ncount %d\n", countmax);
}
抱歉,文字太多了。任何帮助都将不胜感激!
最佳答案
下面是您的函数的固定版本,其中包含一些注释:
int num = 0, curr = -1, currCnt = 0, maxCnt = 0, maxCntCnt = 0;
printf("Please enter positive integers: ");
while (num >= 0) {
if (scanf("%d", &num) != 1)
break;
if (num <= 0)
break;
if (num == curr) {
currCnt++; // new number is continuation of sequence, increase counter
if (currCnt == maxCnt) {
maxCntCnt++; // we're reached previously detected max, increase counter
}
if (currCnt > maxCnt) {
maxCnt = currCnt; // we're reached new max, reset counter
maxCntCnt = 1;
}
} else {
curr = num; // start of new sequence detected, reset counter
currCnt = 1;
}
}
printf("\nmaximum length - %d\n", maxCnt);
printf("occured - %d\n", maxCntCnt);