2011-08-21 63 views
1

你好傢伙我正在寫一個程序的測試文件。所有可能的數字都經過測試,我希望將結果記錄爲.csv文件,因此我可以將其上傳到excel。文件輸出爲.csv目標C

float calc (float i, float j , float p, float ex){ 

    float nodalatio = (p/ex); 

    float ans = (0.68 *j + 1.22*nodalatio + 0.34*j -0.81); 

    return ans; 

} 

int main (int argc, const char * argv[]) 
{ 

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    float stage , grade, pos, ex; 
    float resul; 


    for (int i=1;i<=3;i++){ 
     stage = i; 

     for(int j=1;j<=3;j++){ 
      grade = j; 
      for(int p=1;p<=60;p++){ 
       pos = p; 
       for(int e=1;e<=60;e++){ 

        ex=e; 
        resul = calc(stage, grade,pos,ex); 
        NSLog(@"stage is %f grade is %f,pos is %f ex is %f the result is %f",stage,grade,pos,ex,resul); 



       } 

      } 

     } 
    } 
    [pool drain]; 
    return 0; 
} 

上面是測試代碼,我似乎無法計算如何將其輸出到.csv文件。在循環中或在循環之後執行代碼。這是我的,但這沒有做任何事情!

NSString *file_path = @"test.csv"; 
NSString *test_1 = [NSString [email protected]"%f",resu]; 
[test_1 writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil]; 

謝謝

回答

1

試試這個:

float calc(float, float, float, float); 

float calc (float i, float j , float p, float ex) 
{ 
    float nodalratio = (p/ex); 
    float ans = (0.68 * j + 1.22 * nodalratio + 0.34 * j - 0.81); 
    return ans; 
} 

int main (int argc, const char * argv[]) 
{ 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    float stage , grade, pos, ex; 
    float resul; 

    [[NSFileManager defaultManager] createFileAtPath: @"test.csv" contents: [@"" dataUsingEncoding: NSUnicodeStringEncoding] attributes: nil]; 
    NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath: @"test.csv"]; 
    [file seekToEndOfFile]; 

    for (int i = 1; i <= 3; i++) 
    { 
     stage = i; 
     for(int j = 1; j <= 3; j++) 
     { 
      grade = j; 
      for(int p = 1; p <= 60; p++) 
      { 
       pos = p; 
       for(int e = 1; e <= 60; e++) 
       { 
        ex = e; 
        resul = calc(stage, grade, pos, ex); 

        NSString *str = [NSString stringWithFormat: @"%f, %f, %f, %f, %f\n", stage, grade, pos, ex, resul]; 
        [file writeData: [str dataUsingEncoding: NSUTF16LittleEndianStringEncoding]];     
       } 
      } 
     } 
    } 

    [file closeFile]; 

    [pool drain]; 
    return 0; 
} 

這對我的作品。它將包含一個適當的BOM並以UTF-16(Unicode)編寫每個字符串。使用其他編碼,比如NSUTF16StringEncoding,會爲每一行編寫一個BOM,這實際上並不是你想要的。


FWIW,你確定它不是0.68 * j0.34 * i或反之亦然?

+0

謝謝@Rudy,是的,這是代碼中的拼寫錯誤。我後來發現,當結果在各地的地方xD – cyberbemon

+0

ohk我試着運行上面的代碼。首先我做了一個空文件,並命名爲test.csv,然後我運行代碼..但我只得到一個空文件。沒有什麼! – cyberbemon

+0

嗯...再次移除文件並找出真正的''test.csv「'所在的位置:在Xcode中,在** Products **下的左側樹中搜索.app,然後選擇* *從上下文菜單中打開Finder **。 '「test.csv」'在同一個目錄下。你創建的test.csv實際上是空的,但這可能與程序編寫的「test.csv」不一樣。如果你想在其他地方,那麼也要指定一個目錄,例如' 「/Users/cybermon/test.csv」'。 –