So I calculated the mean and standard deviation from double values read within a file.
My file data has 1 number per line:
My data in the file is the following
1
2
3
4
5
6
7
8
9
10
My code is below:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
FILE *inputfile;
char name[100];
printf("Enter the file you want to use to calculate standard deviation:\n ");
gets(name);
inputfile = fopen(name, "r");
if (inputfile == NULL)
{
printf("Failed to open text file.\n");
exit(1);
}
double i;
double j=1;
double average;
double stdish=0;
double stdreal=0;
double x=0;
double sum=0;
double stdfinal;
while(fscanf(inputfile, "%lf", &i) != EOF){
x=x+1;
sum = sum + i;
j =pow(i,2);
stdreal +=j;
}
average = sum/x;
stdish = (stdreal/x)-(pow(average,2));
stdfinal = sqrt(stdish);
printf("The average is %.4lf\n", average);
printf("The standard deviation is %.4lf\n", stdfinal);
return 0;
}
My standard deviation is incorrect, and I am not sure why.
In my program, I use fopen to get the text from the input file.
Also, I am trying to make it so that I input the text file from the terminal instead of in the actual program itself. How to do that?
First you need to find out the average (mean) and then iterate through the loop to find out the variance. The SQRT(variance) will give you standard deviation.
double CalculateMean()
{
double sum = 0;
for(int i = 0; i < max; i++)
sum += value[i];
return (sum / max);
}
double CalculateVariane()
{
mean = CalculateMean();
double temp = 0;
for(int i = 0; i < max; i++)
{
temp += (value[i] - mean) * (value[i] - mean) ;
}
return temp / max;
}
Reference: http://www.softwareandfinance.com/CPP/MeanVarianceStdDevi.html
Declare main as int main(int argc, char *argv[]) or as int main(int argc, char **argv). They mean the same thing. In this version, argc is the number of command line arguments (+1 because the program name is argument 0). argv is an array of char *s, each of which is a command line argument.
You can do something like this:
int main(int argc, char *argv[])
{
FILE *inputfile;
char name[100];
if(argc == 1) {
printf("Enter the file you want to use to calculate standard deviation:\n ");
gets(name);
} else {
strcpy(name, argv[1]);
}
inputfile = fopen(name, "r");
if (inputfile == NULL)
{
printf("Failed to open text file.\n");
exit(1);
}
double i;
double j=1;
double average;
double stdish=0;
double stdreal=0;
double x=0;
double sum=0;
double stdfinal;
while(fscanf(inputfile, "%lf", &i) != EOF){
x=x+1;
sum = sum + i;
j =pow(i,2);
stdreal +=j;
}
average = sum/x;
stdish = (stdreal/x)-(pow(average,2));
stdfinal = sqrt(stdish);
printf("The average is %.4lf\n", average);
printf("The standard deviation is %.4lf\n", stdfinal);
return 0;
}
Related
I was hoping to get a bit of help, I am implementing an inversion counter algorithm to take in 50,000 intergers and display the inversions and time it took to run the algorithm, I am having a hard time allocating and saving the integers from the file into an array. My code complies and runs but nothing happens
here is what I have:
int main(int argc, char** argv)
{
int n, i;
int inversions=0;
int *A;
FILE *file;
char filename[100];
clock_t start, end;
double totalTime;
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if(file == NULL)
{
printf("Error opening file!\n");
return 0;
}
fscanf(file, "%d", &n);
A = (int*) malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
fscanf(file, "%d", &A[i]);
}
start = clock();
inversions = countInversionsBruteForce(A, n);
end = clock();
totalTime = (double) (end - start) / CLOCKS_PER_SEC;
printf("Brute Force Algorithm\n");
printf("Number of inversions: %d\n", inversions);
printf("Execution time: %f\n", totalTime);
I think I have noth allocated array size and saved it properly
Your program is incomplete so I was not able to compile it. Minimized the problem to just loading the data into your array:
Formatted code for readability.
Generated a suitable input file. Most likely this is your problem but you have not shared your input sample with us.
Added missing include files.
Remove argc, argv as you not using them.
Minimize scope of variables. Use size_t instead of int for unsigned values.
Max string size on obtaining file name
Check return value for scanf(), fopen(), fscanf().
Printing out the data read to demonstrate it's working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("Enter filename: ");
char filename[100];
if(scanf("%99s", filename) != 1) {
printf("scanf failed\n");
return 1;
}
FILE *file = fopen(filename, "r");
if(!file) {
printf("Error opening file!\n");
return 1;
}
size_t n;
fscanf(file, "%zu", &n);
if(!n) {
printf("n must be positive");
return 1;
}
int *A = malloc(n * sizeof(*A));
for(size_t i = 0; i < n; i++)
if(fscanf(file, "%d", &A[i]) != 1) {
printf("fscanf() failed\n");
return 1;
}
printf("n = %zu\n", n);
printf("A = ");
for(size_t i = 0; i < n; i++)
printf("%d%s", A[i], i + 1 < n ? ", " : "\n");
}
with 1.txt as:
4
1
2
3
4
a sample session looks like this:
Enter filename: 1.txt
n = 4
A = 1, 2, 3, 4
I read from txt pairs of numbers
How check it only 2 numbers in each line and not 3. I want show the line is the problem for example the pairs file:
3
25 35
14 42
30 60 70
Console: illegal input at line 4
I know That's not the correct way at all. Need use fgets to read and sscanf to parse.
I tried but the memory full garbage. How can I change it correctly?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, c;
FILE *fp;
char str[100];
fp = fopen("./pairs.txt", "r");
if (dup2(fileno(fp), STDIN_FILENO < 0))
{
printf("Error opening file");
return -1;
}
if (feof(fp))
printf("Error reading file");
scanf("%d", &numOfPairs);
arrNum = (int *)malloc(sizeof(int) * numOfPairs * numbersInPair);
for (int i = 0; i < numOfPairs * numbersInPair; i += 2)
{
int num1, num2;
scanf("%d %d", &num1, &num2);
arrNum[i] = num1;
arrNum[i + 1] = num2;
}
}
Another try NOT working:
int main(int argc, char *argv[])
{
int index, i, numOfPairs;
int c;
FILE *file;
file = fopen("./pairs.txt", "r");
if ((c = getc(file)) == EOF)
{
perror("Error opening file"); //or return 1;
fclose(file);
}
while ((c = getc(file)) != EOF)
putchar(c);
{
fscanf(file, "%d", &numOfPairs);
allNumbers = (int *)malloc(sizeof(int) * numOfPairs * numbersInPair); //need multiply in 2 numbers for each pair
while (!feof(file) && numOfPairs > 0)
{
int x, y, arrIndex = 0;
numOfPairs--;
fscanf(file, "%d %d", &x, &y);
allNumbers[arrIndex] = x;
printf("The X : %d\n", x);
allNumbers[arrIndex + 1] = y;
printf("THE Y : %d\n", y);
arrIndex + 2;
}
fclose(file);
}
So i have een solving a problem where i have to find the prime numbers from the input file and save those prime numbers in an output file called output.txt.But If there are no prime numbers in the input file, i'll have to write “No prime numbers found” in the output file.So when i completed the code when there is no prime number it shows No prime numbers found 5-6 times and i only want it to appear 1 time.What is my mistake here?I am totally a noob here
#include <stdio.h>
#include <stdlib.h>
int Primecheck(const int number);
int main()
{
FILE* Number,
* Prime_N;
int num;
char sentence[50] = "No prime numbers found";
int length = strlen(sentence);
int i;
Number = fopen("input.txt", "r");
Prime_N = fopen("output.txt", "w");
if (Number == NULL || Prime_N == NULL)
{
printf("Unable to open file.\n");
exit(EXIT_FAILURE);
}
printf("File opened and Reading Done \n\n");
while (fscanf(Number, "%d", &num) != -1)
{
if (Primecheck(num) == 1)
fprintf(Prime_N, "%d\n", num);
else
for (i = 0; i < length; i++)
{
fputc(sentence[i], Prime_N);
}
}
fclose(Number);
fclose(Prime_N);
printf("Overwrite Success.");
return 0;
}
int Primecheck(const int number)
{
int i;
if (number < 0)
return 0;
for (i = 2; i <= number / 2; i++)
{
if (number % i == 0)
{
return 0;
}
}
return 1;
}
instead of
else
for(i=0;i<length;i++)
{
fputc(sentence[i] ,Prime_N);
}
you can just write
else
printf("No prime numbers found");
Well , as I see from your code , each time you read a number from the file you check if prime write it or write sentence . so of course you get multiple output ,
you should write the number to char* then check if changed after reading from Number and checking if prime write the number in the char* after the loop just check if the length of the char* that you stored the primes in it if changed write it else write your sentence ... Done
something like this
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef struct {
char* data;
size_t size;
size_t capacity;
} string;
void init_string(string* s, size_t size){
s->data = (char*)malloc(sizeof(char) * size);
s->capacity = size;
s->size = 0;
}
void append(string* s,const char* str){
if(s->capacity - s->size < strlen(str)){
s->data = (char*)realloc(s->data, sizeof(char)* 4 * strlen(str));
}strcat(s->data, str);
}
void free_string(string* s){
free(s->data);
}
int is_odd(int n){
return n%2;
}
int main(){
int num[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
string str;
init_string(&str,1);
char* snum;
for(int i=0; i<18; i++){
if(!is_odd(i)){
sprintf(snum,"%d",num[i]);
append(&str, snum);
append(&str, "\n");
}
//printf(snum);
//strcat(str, snum);
}
printf("%s",str.data);
free_string(&str);
//printf(str);
return 0;
}
*this program read integers until one is negative then prints on a file a characteristic of each of them: how many integers it can be divided by. the problem is that it keeps asking for integers even when i inseert negative ones. please let me know if you can a way to fix this without changing too much of the code
#include <stdio.h>
#include <stdlib.h>
int checkdiv(int *n);
int main(int argc, char * argv[]){
int *p;
int i, j;
FILE *fp;
int amount;
i=0;
p=NULL;
if(fp = fopen("ris.txt", "w")){
do{i++;
p=realloc(p,sizeof(int)*i);
scanf("%d", (p+i-1));
amount=checkdiv(p+i-1);
if(amount!= -1);
fprintf(fp,"%d %d\n", *(p+i-1),amount);
}while(p+i-1>0);
}else{
printf("errore");
}
fclose(fp);
free(p);
return 0;
}
int checkdiv(int *n){
int i;
int amount=0;
for(i = 2;i < *n; i++){
if(*n % i == 0){
amount++;
}
}
if(*n <= 0){
amount= -1;
}
return amount;
}
Your problem is in:
}while(p+i-1>0);
must be;
}while(*(p+i-1)>0);
HTH
You should remove semi colon in line
if(amount!=-1);
so that the statement below it can be included in if block.
I have to find the average of double numbers that the user inputs at the command line, so my program should work with any amount of inputs. I understand that I have to find the sum of all of the numbers and then divide by the number of inputs.
I was thinking, to find the number of inputs, I would use sscanf to read "char *num" in my argument list. Because sscanf returns the characters read. And then I was thinking of using that to divide the sum by to get the average. But I'm having trouble with my code. :(
#include <stdio.h>
void average(int arg_list, char *num[])
{
int x;
double sum, average;
x = sscanf(num, "%s\n", &x);
for (int i = 0; i != '\0'; i++)
{
sum = sum + num[i];
}
average = sum/x;
printf("%lf\n", average);;
}
int main(int argc, char *argv[])
{
if (argc == 0)
{
perror("Error!\n");
}
average(argc, argv);
}
Specifically, when I try to compile my program, the compiler complains about the "sscanf" and the sum. :/
"%s" reads a string. you want to read a double out of the string, so you should use "%lf". inside the loop:
double sum = 0; //you forgot to initialize
//start from i=1, not 0; the first argument is the program's name
for (int i = 1; i < arg_list; i++) {
double x;
//from the i'th argument, read a double, into x :
sscanf(num[i], "%lf", &x);
sum += x;
}
average = sum/(arg_list-1);
you should also fix your check:
if (argc <= 1) {
perror("Error!\n");
}
#include <stdio.h>
#include <stdlib.h>
void average(int arg_list, char *num[])
{
double sum = 0, average;//sum : 0 initialize
int i;
for (i = 1; i < arg_list; i++){
sum = sum + atof(num[i]);
}
average = sum/(--i);
printf("%lf\n", average);;
}
int main(int argc, char *argv[])
{
if (argc < 2)//include program name argv[0], argc == 1 even when only ./a.out
{
perror("Error!\n");
return -1;
}
average(argc, argv);
return 0;
}