我对C编码很陌生,我设计了一个程序,只要用户输入1,2或3就执行某项任务。我有一个80 X值的数据集,对应80 Y值,首先我需要至;找到最小/最大Y值并将其打印到具有相应X值的文件中,对数据文件进行数值积分,然后查找值的均值/标准偏差。基本上我生成的代码将运行程序,但是当输入1,2或3时,它将不会运行任何函数,并将要求另一个值。
就像我说的,我是新手,所以我知道我不会第一次得到它。
#include <Math.h>
#include <stdio.h>
const int X = 1001; // will be used to define number of rows in array
const int Y = 2; // equally used to define columns
void writeTwoToFile(int answer1, int answer2) {
FILE* answers;
answers = fopen("answer.txt", "w");
fprintf(answers, "The first answer is: %d\n The second answer is: %d\n",
answer1, answer2);
}
void writeToFile(int answer) {
FILE* answers;
answers = fopen("answer.txt", "w");
fprintf(answers, "The first answer is: %d\n", answer);
}
void max(int dataArray[X][Y]) {
int col = 1;
int smallest = 0;
int largest = 0;
for (int i = 0; i < 1000; i++) {
if (dataArray[col][i] > largest) {
largest = dataArray[col][i];
} else if (dataArray[col][i] < smallest) {
smallest = dataArray[col][i];
}
}
writeTwoToFile(smallest, largest);
}
void integrate(int dataArray[X][Y]) {
int answer = 0;
for (int i = 0; i < 80; i++) {
if (i == 0 || i == 79) {
answer += dataArray[1][i];
} else if (i % 2 == 1) { //% is a modulo function, does a division and
returns the remainder,
easy way of alternating numbers-- answer += dataArray[1][i] * 2;
} else {
answer += dataArray[1][i] * 4;
}
}
answer / 12;
writeToFile(answer);
}
void mean(int dataArray[X][Y]) {
int mean = 0;
int stdDeviation = 0;
for (int i = 0; i < 1000; i++) {
mean += dataArray[1][i];
}
mean / 80;
for (int j = 0; j < 1000; j++) {
stdDeviation += pow(dataArray[1][j] - mean, 2);
}
stdDeviation / 79;
sqrt(stdDeviation);
writeTwoToFile(mean, stdDeviation);
}
int main() {
int loop = 0; // act as a loop counter
int user; // to collect user input
int dataArray[X][Y]; // array data is to be stored in
// Open and read file
FILE* data;
data = fopen("data.dat", "r");
// Read file in to 2D array, 2-1000 matrix essentially
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 1000; j++) {
fscanf(data, "%1d", &dataArray[j][i]);
}
}
printf("Welcome to this calculator, please input one of the following "
"numbers\n");
printf("1- Find maximum and minimum\n");
printf("2- Find definite integral\n");
printf("3- Calculate the mean and standard deviation\n");
printf("\n");
while (loop == 0) {
printf("Please input the number you want to manipulate\n");
scanf("%d", &user); // takes user input
if (user == 1) {
max(dataArray);
}
else if (user == 2) {
integrate(dataArray);
}
else if (user == 3) {
mean(dataArray);
}
else {
printf("Please enter a valid number");
}
}
}
感谢您的任何帮助。
答案 0 :(得分:5)
你有一个无限循环。
代码行:
while(loop==0)
主方法中的将始终评估为true,因为您永远不会增加变量loop
。
您应该使用for循环,或在每个输入案例中增加loop
。