簡體   English   中英

如何一次掃描輸入,一次處理3個,處理它們,然后繼續掃描C中的其余輸入

[英]how to scanf inputs, 3 at a time, process them, then continue scanf the rest of input in C

#include <stdio.h>

#define ROWS 3
#define COLS 3


void assign(double A[][COLS], double nrows);
void print(double A[][COLS], double nrows);


int main(int argc, char* argv[]){
    double A[ROWS][COLS];
    assign(A, ROWS);
    print(A, ROWS);
    return 0;
}


void
assign(double A[][COLS], double nrows){
    double mass, velocity_terminal, area;
    while(scanf("%lf, %lf, %lf", &mass, &velocity_terminal, &area)==3){
    int i;
    for (i= 0; i<nrows; i++){
                A[i][0]= mass;
                A[i][1]= velocity_terminal;
                A[i][2]= area;
    }
        }
    }

void
print(double A[][COLS], double nrows){
    int i, j;
    for(i=0; i<nrows; i++){
        for(j=0; j<nrows; j++){
            printf("%5lf",A[i][j]);
        }
        printf("\n");
    }

}

我很抱歉格式化。 目的是將輸入排列成二維數組。 我正在嘗試從提示中的文本文件中讀取輸入的內容。 因此一次取3個並分配給各個地方。 上面的代碼僅將最后3個輸入放入數組。

問題是您主要在scanf()上循環,但是在每次迭代中,for循環都會將las值設置為讀取所有元素!

最簡單的修正是:

   int i=0;    // declare outside the loop and start with first element
   while(scanf("%lf, %lf, %lf", &mass, &velocity_terminal, &area)==3 && i<nrows){ // make sure that you don't go out of nrow range
          A[i][0]= mass;
          A[i][1]= velocity_terminal;
          A[i][2]= area;
          i++;
    }

現在,當您接受值時,while循環會很好。 但是實際上您錯過的是您在While中編寫了for循環,這就是為什么它每次都覆蓋數據時意味着沒有編寫代碼的原因:

void assign(double A[][COLS], double nrows){
double mass, velocity_terminal, area;
while(scanf("%lf, %lf, %lf", &mass, &velocity_terminal, &area)==3){
int i;
for (i= 0; i<nrows; i++){
            A[i][0]= mass;
            A[i][1]= velocity_terminal;
            A[i][2]= area;
}
    }
}

您需要寫:

void assign(double A[][COLS], double nrows){
double mass, velocity_terminal, area;
int i=0;
while(scanf("%lf, %lf, %lf", &mass, &velocity_terminal, &area)==3){       
            A[i][0]= mass;
            A[i][1]= velocity_terminal;
            A[i++][2]= area;

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM