Files
CONTROLE_DEV51_vaisse/exo2/racine.c

76 lines
1.6 KiB
C
Raw Normal View History

2025-10-15 16:53:33 +02:00
#include <stdlib.h>
#include <stdio.h>
#define LIMIT 1000
#define BUF_LIM 512
long racineCarree(long n){
for(long i=0; i<(n/2); i++){
if((i*i)==n){
return i;
}
}
return -1;
}
long* racineCarreeTab(long* tab, int count){
long* rst = (long*) malloc(LIMIT*sizeof(long));
for(long i=0; i<count; i++){
rst[i] = racineCarree(tab[i]);
}
return rst;
}
int main(int argc, char** argv){
/*variables*/
long* tab = (long*) malloc(LIMIT*sizeof(long));
long* rst = (long*) malloc(LIMIT*sizeof(long));
int count = 0;
char * buffer = (char*) malloc(BUF_LIM*sizeof(char));
FILE* f = fopen(argv[1], "r");
unsigned short hasfile = 0;
/*tests*/
if(argc < 2){
printf("USAGE:./a.out <entier(s) strictement(s) positif(s)>\n");
printf("USAGE:./a.out <fichier>\n");
return EXIT_FAILURE;
}
if(f!=NULL){
while(fgets(buffer, BUF_LIM*sizeof(char), f)){
tab[count] = strtol(buffer, NULL, 10);
count++;
}
fclose(f);
hasfile = 1;
} else {
for(int i=1; i<argc; i++){
if((strtol(argv[i], NULL, 10)<0)||(strtol(argv[i], NULL, 10)==0L)){
printf("FORMAT:entier strictement positif\n");
return EXIT_FAILURE;
}
tab[i-1] = strtol(argv[i], NULL, 10);
count++;
}
}
/*prog*/
if((argc == 2)&&(hasfile!=1)){
printf("racineCarree de %ld = %ld\n", strtol(argv[1], NULL, 10), racineCarree(strtol(argv[1], NULL, 10)));
} else {
rst = racineCarreeTab(tab, count);
printf("racineCarreeTab : \n");
for(int i=0; i<count; i++){
printf(" . racine de %ld = %ld\n", tab[i], rst[i]);
}
}
free(rst);
free(tab);
free(buffer);
return EXIT_SUCCESS;
}