*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.
Related
#include <stdio.h>
int main()
{
int input;
int result = 1;
printf("Enter the integer number : ");
scanf("%d", &input);
printf("n:!\n\n");
for(int i = 1; i <= input; i = i + 2)
{
for(int k = 1; k <= i; k++)
{
result *= k;
}
printf("%d:%d\n", i, result);
}
return 0;
}
I have created such code to determine the factorial of input's odd number. During the testing, I have found out that beyond the factorial of 5, the value gets wrong. Seems like the calculation is going wrong but I don't know what is the problem in my code.
your problem is you are multiplying result with the old value it has in each inner loop. to solve this before the start of inner loop reset result to 1 by :
result = 1;
and this is not related to the question but I prefer to avoid this algorithm as it is O(n^2 /2) we can consider it O(n^2), rather you can use this one it is O(n) :
#include <stdio.h>
int main()
{
int input;
long double result = 1;
printf("Enter the integer number : ");
scanf("%d", &input);
printf("n:!\n\n");
for(int i = 1; i <= input; i++)
{
result *= i;
if(i%2==1){ printf("%d:%Le\n", i, result); } //note that im using %Le for long double type
}
also be careful with int type you are using for result, int is limited you should use long double because fact operation's result will be big
Firstly, it's probably best not to use scanf for ill defined data such as user input. In fact, the rule "don't use scanf" very often valid. A program such as this might be better off using a command line argument instead.
Technically in C main should be int main(void) or some variation of int main(int argc, char *argv[].
As others have mentioned, it would be more reasonable to use unsigned integers for a calculation like this where negative numbers are impossible. For something like a factorial it would make sense to use a larger integer type too.
Anyway, on topic: why don't you do it more simply? The factorial function can be iterated in one loop. If you only want to print the result when i is odd, just check whether it's odd.
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static unsigned get_input(void);
static unsigned interpret_string(const char *str);
int
main(int argc, char *argv[])
{
unsigned input;
uint64_t result = 1;
if (argc == 1) {
printf("Enter the integer number : ");
input = get_input();
putchar('\n');
} else {
input = interpret_string(argv[1]);
}
for (unsigned i = 1; i <= input; ++i) {
result *= i;
if (i & 1)
printf("%-2d = %"PRIu64"\n", (int)i, result);
}
return 0;
}
static unsigned
interpret_string(const char *str)
{
char *endp = NULL;
unsigned ret = strtoll(str, &endp, 10);
if (endp == str) {
fprintf(stderr, "Invalid input \"%s\"\n", str);
exit(1);
}
return ret;
}
static unsigned
get_input(void)
{
char buf[1024];
fgets(buf, 1024, stdin);
return interpret_string(buf);
}
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;
}
I keep getting a Seg fault on line 51 fscanf(fp, "%d", lenPtr). Everytime I run the program, "1" is printed, but it never gets to 2 before seg faulting. I have done this many times, and cannot seem to figure out the trouble. I know it is incorrect, but when I replace line 51 with fscanf(fp,"%d", *lenPtr);, it doesn't cause a segmentation fault.
//Brendan Sullivan
//Section D
//Prelab 5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {
PENNY = 1,
NICKEL = 2,
DIME = 10,
QUARTER = 25,
} Denomination;
typedef struct {
Denomination denomination;
int quantity;
} Coin;
typedef Coin *PiggyBank;
PiggyBank loadBank(const char *filename, int *lenPtr);
int totalMoney(PiggyBank bank, int length);
int main(int argc, char *argv[]) {
int *length;
PiggyBank piggyBank = loadBank(argv[1], length);
/*for (i = 0; i < (*lenPtr); i++) {
printf("%d %d", piggyBank[i].denomination, piggyBank[i].quantity);
}*/
return 0;
}
PiggyBank loadBank(const char *filename, int *lenPtr) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("File could not be opened\n");
*lenPtr = 0;
return NULL;
}
printf("1\n");
fscanf(fp, "%d", lenPtr); //Line 51
printf("2\n");
printf("%d\n", *lenPtr);
PiggyBank piggyBank = malloc(sizeof(Coin) * (*lenPtr));
int i;
for (i = 0; i < *lenPtr; i++) {
fscanf(fp,"%u %d", &piggyBank[i].denomination, &piggyBank[i].quantity);
}
return piggyBank;
fclose(fp);
}
You call loadBank with a uninitialized int* length as the destination pointer. Undefined behavior ensues. You should instead to this:
int main(int argc, char *argv[]) {
int i, length;
PiggyBank piggyBank = loadBank(argv[1], &length);
for (i = 0; i < length; i++) {
printf("%d %d\n", piggyBank[i].denomination, piggyBank[i].quantity);
}
return 0;
}
Note that the code in loadBank does not allocate anything and returns an undefined variable piggyBank in the middle of the function. Either your code does not compile or you are not posting it correctly.
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;
}
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;
}