当我执行我的代码时,我会一直得到正确的答案,但它会被多次打印?我希望它显示一个包含5列和3行的表格,应该有4个这样的表但我得到的次数太多而我不知道为什么?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int w;
int n = 1;
int i;
for(w = 1; w < 5; w++){
FILE *myFile;
float numberArray[1];
if(n == 4){
myFile = fopen("input4.txt", "r");
n++;
}
if(n == 3){
myFile = fopen("input3.txt", "r");
n++;
}
if(n == 2){
myFile = fopen("input2.txt", "r");
n++;
}
if(n == 1){
myFile = fopen("input1.txt", "r");
n++;
}
if (myFile == NULL)
{
printf("Error Reading File\n");
exit (0);
}
printf("Enter 3 numbers between 0 and 9.999:\n");
printf("Number sin cos tan atan\n");
printf("-------------------------------------------\n");
for (i = 0; i < 3; i++)
{
fscanf(myFile, "%f,", &numberArray[i] );
}
for (i = 0; i < 3; i++)
{
printf("%.6f %.4f %.4f %.4f %.4f\n",numberArray[i], sin(numberArray[i]), cos(numberArray[i]), tan(numberArray[i]), atan(numberArray[i]));
}
fclose(myFile);
}
return 0;
}
答案 0 :(得分:0)
访问numberArray时,您正在读取和写入未分配的内存空间。
你定义了numberArray [1],大小为1,但你在循环中访问numberArray [1..2]:
for (i = 0; i < 3; i++)
{
fscanf(myFile, "%f,", &numberArray[i] );
}
for (i = 0; i < 3; i++)
{
printf("%.6f %.4f %.4f %.4f %.4f\n",numberArray[i], sin(numberArray[i]), cos(numberArray[i]), tan(numberArray[i]), atan(numberArray[i]));
}
我没有测试过您的代码,但这似乎是最明显的罪魁祸首。