2016-12-01 30 views
1

我有一個數組的初始化爲包含50個元素的輸入函數。對從用戶收集輸入終止一旦值「-1」的進入循環和50項在輸入如何根據特定的輸入和大小獲取數組的輸入函數以終止?

爲了正確地測試該程序我有這些2測試用例:

  1. 輸入的值不足50個,數據集以「-1」結尾。
  2. 有50個值輸入,數據集不以「-1」結尾。

我能夠得到第一個測試用例的工作,但對於第二個測試用例,它似乎進入了一個無限循環。我如何修改我的輸入函數以便爲第二個測試用例工作?

主要功能:

#include<stdio.h> 
#include<stdlib.h> 
//Global Declarations 
#define SIZE 50 

int getFuelRange(); 
int getStartMile(); 
void getMileMarkers(int markers[], int*); 
void bubbleSort(int markers[], int); 
int searchArray(int markers[], int, int); 
int calcDifference(int markers[], int, int, int); 
int findSize(int markers[]); 
//void displayResults(); 

int main() 
{ 
    //Local Declarations 
    int fuelRange; 
    int startMile; 
    int markers[SIZE]; 
    int i = 0; 
    int points; 
    int size; 

    //Executable Statements 
    fuelRange = getFuelRange(); 
    startMile = getStartMile(); 
    getMileMarkers(&markers[i], &size); 
    //Diagnostics 
    //printf("\nFuel Range: %d Start Mile: %d\n", fuelRange, startMile); 
    //printf("\nSize: %d \n", size); 
    points = calcDifference(&markers[i], fuelRange, startMile, size); 


    //Diagnostics 
    //printf("\nFuel Range: %d Start Mile: %d\n", fuelRange, startMile); 
    printf("Points: %d \n", points); 

    return(0); 
} 

輸入功能:

void getMileMarkers(int markers[], int *size) 
{ 
    //LOCAL DECLARATIONS 
    int i = -1; //counter 
    //EXECUTABLE STATEMENTS 
    printf("Enter mile marker positions: "); 
    do 
    { 
    i++; 
    scanf("%d", &markers[i]); 
    //Diagnostic Print 
    printf("\n%d", markers[i]); 
    }while(markers[i] != -1 && i < SIZE); 
    (*size) = i; 
} 

任何幫助表示讚賞!謝謝!

回答

3

更容易和更具可讀性只是有一個do循環和退出,如果標記被發現:

for (i=0; i < SIZE; i++) { 
    scanf("%d", &markers[i]); 
    if (markers[i] == -1) { 
     break; 
    } 
} 
+0

我唯一的問題是,我不能用break語句,所以我能不能替換通過設置i = SIZE? –

+0

現在有用,謝謝! –

相關問題