大家好我正在为程序编写测试文件。所有可能的数字都经过测试,我希望将结果记录为.csv文件,这样我就可以将其上传到excel中。
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 stringwithformat@"%f",resu];
[test_1 writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
谢谢
答案 0 :(得分: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 * j
和0.34 * i
,反之亦然?
答案 1 :(得分:1)