如何在for循环中获得0作为最后一个数字? [英] how to get 0 as last number in for loop?

查看:164
本文介绍了如何在for循环中获得0作为最后一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在c ++中打招呼,

我从下面链接写程序:

遇到麻烦寻找最大值,最小值(ARRAY)[^] [ ^ ]



这个工作正常但是我想改变程序如下:

例如当用户输入10个数字来获得min&最后一个数字应该是0.

我的意思是最后一个数字应该是0,如果它不是错误就出现了。

Hey
I ''m begginer in c++,
I write program from below link:
Having Trouble Finding Maximum, Minimum (A R R A Y)[^][^]

this works fine but I want to change the program as below:
for example when user enter 10 number to get min & max the last number should be 0.
I mean the last number should be 0 and if it''s not an error shows up.

推荐答案

问题是什么?只需检查 a [length-1] == 0 ,即

And what''s the problem? Just check if a[length-1] == 0, namely
if ( a[length-1] == 0)
{
  // OK
}
else
{
  // handle error
}






应该是相当容易。您只需使用 while 循环来完成arroy,当您找到零时,循环结束:

Hi,

that should be fairly easy. You just use a while loop to go through the arroy and when you find zero, the loop ends:
#include <stdlib.h>
#include <stdlio.h>
#include <limits.h>

// function that finds and prints the MIN and MAX array value
void FindMinAndMax(int* array, int length)
{
   int Min = INT_MAX; 
   int Max = INT_MIN;

   // here we check for the error
   if (array[length-1] != 0)
   {
      printf("Error: Array must end with 0 !!!");
      return ;
   }

   int i = 0;
   while (array[i] != 0)
   {
       if (array[i] > Max)
           Max = array[i]; 

       if (array[i] < Min)
           Min = array[i];   

       i++;     
   }
   
   printf("Min = %d\n", Min);
   printf("Max = %d\n", Max);
}



希望这会有所帮助。



祝你好运。

JK


Hope this helps.

Best regards.
J.K.


这篇关于如何在for循环中获得0作为最后一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆