我需要输入一个数字(用户输入-1
退出),程序需要判断它是否增加了单调序列。
我是在do-while
循环中完成的,我知道如果我想检查它是否正在增加,我需要检查之前的数字,然后比较previous
和current
数字。
但是,我很难想象循环的过程。
以下是代码:
#include <stdio.h>
void main()
{
int num, i = 0, numPrev = 0;
printf("Enter a number:");
do {
scanf("%d", &num);
numPrev = num;
i++;
if (num > numPrev)
} while (num != -1);
printf("The Serias is Monotinic Acsending\n");
}
答案 0 :(得分:0)
您应该进行以下更改。我已根据需要添加了评论。假设您希望阅读整个输入!
#include <stdio.h>
int main(void)//refer the link given below
{
int i = 0, numCurr, numPrev = 0; //for storing current no. and previous no.
int flag = 0;
printf("Enter input:");
do {
scanf("%d", &numCurr);
if(i != 0 && numCurr != -1 && numPrev > numCurr)//so that comparison begins from the second element
flag = 1;
numPrev = numCurr;
i++;
} while (numCurr != -1);
if(flag == 0)printf("The Serias is Monotinic Acsending\n");
else printf("The Serias is not Monotinic Acsending\n");
return 0;
}
答案 1 :(得分:0)
关键点:
scanf
返回值)考虑以下代码
#include <stdio.h>
int main(void)
{
int num, i = 0, numPrev = 0;
printf("Enter a number:");
if (!scanf("%d", &numPrev)) return -1;
while (numPrev != -1)
{
if (!scanf("%d", &num)) return -1;
if (num != -1 && num <= numPrev)
{
printf("The Serias is not Monotinic Acsending\n");
return 0;
}
numPrev = num;
}
printf("The Serias is Monotinic Acsending\n");
return 0;
}
如果在找到非单调系列时无法直接返回,则可能需要某种结果变量来决定循环是否被取消(非单调)或完成(单调)。