2011-08-21 115 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”'。 –