So im doing this homework for my programming class, but the data output doesnt match with the theoretical data output that it shoud be printing and it gives me a big number.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void menu(int *);
void CalculoVentas(float ventas[50][7], float ventasXproductos[50], int);
void PromedioDiario(float promedioXdia[7], float ventas[50][7], int);
int main()
{
char ciclos;
int sel, cont = 0, i = 0;
float ventas[50][7], ventasXproductos[50], promedioXdia[7];
bool lectura = false;
while(sel != 5)
{
menu(&sel);
system("cls");
switch(sel)
{
case 1:
printf("Hay Productos?: S/N ");
fflush(stdin);
scanf("%c", &ciclos);
while(ciclos == 's' || ciclos == 'S' && cont < 50)
{
for(i=0;i<7;i++)
{
do
{
printf("Teclea los ingresos generados por el producto %d el dia %d: ", cont+1, i+1);
scanf("%f", &ventas[cont][i]);
}while(ventas[cont][i] < 0);
printf("\n\n");
}
cont++;
system("cls");
printf("Hay Productos?: S/N ");
fflush(stdin);
scanf("%c", &ciclos);
lectura = true;
}
break;
case 2:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
CalculoVentas(ventas, ventasXproductos, cont);
break;
case 3:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
PromedioDiario(promedioXdia, ventas, cont);
break;
case 4:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
printf("%35s\n", "Total de ventas");
for(i=0;i<cont;i++)
printf("%d %.2f\n", i+1, ventasXproductos[i]);
printf("\n\n\n\n");
printf("%35s\n", "Promedio de ventas por dia");
for(i=0;i<7;i++)
printf("Dia %d: %.2f\n", i+1, promedioXdia[i]);
printf("\n\n\n\n");
break;
}
}
}
void menu(int *seleccion)
{
printf("%20s\n%s\n%s\n%s\n%s\n%s\n", "Menu de opciones", "1.-lectura de datos", "2.-calculo de ventas por producto", "3.-promedio de ventas de cada dia", "4.-imprimir resultados", "5.-salir");
do{
printf("Seleccione una opcion: ");
scanf("%d", &*seleccion);
}while(*seleccion <= 0 || *seleccion > 5);
}
void CalculoVentas(float ventas[50][7], float ventasXproducto[50], int cont)
{
//realizar el calculo de ventas por productos, nada más es la suma de las ventas de todos los dias por producto
int i,j;
for (i = 0 ; i<cont ; i++)
for (j = 0 ; j < 7 ; j++)
ventasXproducto[i] = ventasXproducto[i] + ventas[i][j];
}
void PromedioDiario(float promedioXdia[7], float ventas[50][7], int cont)
{
int i,j;
for(i=0;i<7;i++)
{
for(j=0;j<cont; j++)
promedioXdia[i] = promedioXdia[i] + ventas[j][i];
promedioXdia[i] = promedioXdia[i]/cont;
}
}
the output is something like this, I try to type simple data so i can know easly if its wrong
Total de ventas
1 70.00
2 5103881324019006800000000000000000.00
3 210.00
4 280.00
Promedio de ventas por dia
Dia 1: 25.00
Dia 2: 25.00
Dia 3: 25.00
Dia 4: 1291386862541487300000000000000000.00
Dia 5: 25.00
Dia 6: -1.#R
Dia 7: 25.00
when i was trying to get help someone told me that i might be not initializing correctly the variables but i couldnt find any issue with that
When the program begins, sel is uninitialized and contains a garbage value. This garbage value is used in the while condition on its first iteration
while(sel != 5)
and as such invokes Undefined Behaviour.
You must restructure your loop to not read this uninitialized value, or simply initialize sel (to something other than 5).
Similarly, the contents of ventas, ventasXproductos, and promedioXdia are all uninitialized as well.
This means statements such as
ventasXproducto[i] = ventasXproducto[i] + ventas[i][j];
/* ... and ... */
promedioXdia[i] = promedioXdia[i]/cont;
will be operating with garbage values to start.
You can fix this by initializing your arrays:
float ventas[50][7] = { 0 }, ventasXproductos[50] = { 0 }, promedioXdia[7] = { 0 };
You should not ignore the return value of scanf. You should always check that its return value is the expected number of successful conversions, otherwise you will find yourself operating on incomplete data.
/* An example */
if (2 != scanf("%d%d", &num1, &num2)) {
/* handle failure */
}
(Better yet: avoid using scanf, and use fgets and sscanf to read and parse lines of input.)
You should clarify this expression by adding more parenthesis, otherwise you will run into issues with operator precedence:
while ((ciclos == 's' || ciclos == 'S') && cont < 50)
case 4 of the switch has misleading indentation. Only the first statement with the call to printf is contained within the else block. It is read as:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
printf("%35s\n", "Total de ventas");
for(i=0;i<cont;i++)
printf("%d %.2f\n", i+1, ventasXproductos[i]);
/* ... */
Your lectura flag will not protect you from operating on incomplete data if this is selected. Enclose the code with curly braces:
case 4:
if(lectura == false) {
printf("Primero ingresa los datos del producto!!!\n");
} else {
printf("%35s\n", "Total de ventas");
for(i=0;i<cont;i++)
printf("%d %.2f\n", i+1, ventasXproductos[i]);
/* ... */
}
break;
Note that in &*seleccion, & and * balance each other out. This resolves to the same value as just writing seleccion would.
Note that fflush(stdin); is also (technically) Undefined Behaviour, and should not be relied upon.
Hello I'm fairly new to programming so here's my problem, I have multiple arrays of the size x,
I want to add b values to my array, what I did is x + b then ask the user to type his value then call a function that looks if the value is already in the array, if it is, I ask the user to type it again, but the problem is that the search function returns random numbers. heres my code (the fRecherche2 works fine outside of fAjouter):
int fRecherche2 (int ref[],int n,int nref)
{
int i;
for (i=0;i<n;i++)
if (ref[i]==nref)
return i;
return -1;
}
int fAjouter(int ref[],int qt[],float prix[],int sds[],int n)
{
int i,prods,nb,code,nref;
printf("How many products would you like to add:");
scanf("%d",& prods);
fVerifVal(prods);
n=NbArticle();
nb=n+prods;
for(i=n;i<nb;i++)
{
printf("Reference: ");
scanf("%d", &ref[i]);
ref[i]=nref;
code=fRecherche2(ref,n,nref);
printf("%d\n",code);
while(code!=-1)
{
printf("The reference already exists.\n");
printf("Please try again: ");
scanf("%d", &ref[i]);
ref[i]=nref;
code=fRecherche2(ref,n,nref);
printf("%d",code);
if(code==-1)
break;
}
fVerif(ref,i); //Checks if the value is bigger than 0
printf("Amount: ");
scanf("%d", &qt[i]);
fVerif(qt,i);
printf("Price: ");
scanf("%f", &prix[i]);
fVerifReal(prix,i); //Checks if the value is bigger than 0.00
printf("Security threshold: ");
scanf("%d", &sds[i]);
fVerif(sds,i);
}
fEnregNombre(nb); //saves my new size in a file
code=fEnreg(ref,qt,prix,sds,nb); // saves all my new arrays in a file
if(code==-1)
return -1;
}
void fCreerStock (void)
{
int i,n;
printf("Combien d'articles : ");
scanf("%d", &n );
while(n<=1)
{
printf("Il faut au moins 1 article!\n");
printf("Veuillez réesayer: ");
scanf("%d",&n);
if(n>0)
break;
}
FILE * nombre;
nombre=fopen("Nombre_d'article.txt","w");
if (nombre == NULL)
{
printf("probleme d'ouverture du fichier \n");
exit(1);
}
fprintf(nombre,"%d",n);
fclose(nombre);
int ref[n],qt [n], sds [n];
float prix[n];
for (i=0; i<n; i++)
{
printf("reference %d : ", i);
scanf("%d", &ref[i]);
fVerif(ref,i);
printf("quantité %d : ", i);
scanf("%d", &qt[i]);
fVerif(qt,i);
printf("Prix %d : ", i);
scanf("%f", &prix[i]);
fVerifReal(prix,i);
printf("seuil de sécurité %d : ", i);
scanf("%d", &sds[i]);
fVerif(sds,i);
}
FILE * flot;
flot=fopen("nom.txt","a");
if (flot == NULL)
{
printf("Probleme d'ouverture du fichier \n");
exit(1);
}
for (i=0; i<n; i++)
fprintf(flot,"%d\t%d\t%.2f\t%d\n",ref[i],qt[i],prix[i],sds[i]);
fclose(flot);
}
#include <stdio.h>
#include "sae.h"
void globale (void)
{
int n;
n=NbArticle();
int ref[n],qt[n],sds[n],CodeErr,code,CodeSup;
float prix[n];
char choix;
CodeErr=fConsulterStock(ref,qt,prix,sds,n);
printf("\n\nBienvenue a l'application de gestion de stock 'Xtrachaus'\n\n");
if (CodeErr== -1 || n == -1)
printf("!! Vous n'avez pas encore créer de stock veuillez créer un stock avant de faire n'importe quel manipulation !! \n\n");
printf("Créer un stock: 'c'| Afficher le stock: 'o'| Etat du stock: 'e'| Faire le devis d'une commade: 'd'| Récapitulatif des ventes: 'r'| Approvisionnement: 'a'| \nSupprimer un article:'s'| Rechercher un article avec n° ref: 'n'| Modifier l'article :'m'| Ajouter un article: 't'\n\n");
printf("Que voulez vous faire(votre choix): ");
scanf("%c%*c", &choix);
if (choix =='c')
fCreerStock();
if (choix =='o')
fAfficherStock(ref,qt,prix,sds,n);
if (choix =='e')
fEtatStock(ref,qt,prix,sds,n);
/*if (choix =='d')
fDevis();
if (choix =='r')
fVentes();*/
if (choix =='a')
{
fAfficherStock(ref,qt,prix,sds,n);
code=fAppro(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, l'approvisionement ne peut pas s'effectuer.\n");
else
printf("Approvisionement éffectué. \n");
printf("\n");
fAfficherStock(ref,qt,prix,sds,n);
}
if (choix =='s')
{
CodeSup=fSuppression(ref,qt,prix,sds,n);
if(CodeSup!=-1)
printf("Suppression éffectué. \n");
else
printf("Erreur, la suppression ne peut pas s'effectuer.\n");
}
if (choix =='n')
{
code=fRecherche(ref,n);
if (code!=-1)
{
printf("\nReference:\tQuantite:\tPrix:\tSeuil de securite:\n");
printf("%d\t\t%d\t\t%.2f\t\t%d\n" ,ref[code], qt[code], prix[code], sds[code]);
}
else
printf("La réference n'existe pas\n");
}
if (choix =='t')
{
code==fAjouter(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, l'ajout ne peut pas s'effectuer.\n");
else
printf("Ajout éffectué. \n");
}
if (choix =='m')
{
code=fModifier(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, la modification ne peut pas s'effectuer.\n");
else
printf("Modification éffectué. \n");
}
}
int main (void)
{
globale();
return 0;
}
If theres anything else I could provide please tell me! Thanks.
(sorry most of the code and variables are in french i translated the part im stuck at).
edit3:
heres examples of where the program fails:
before adding a value:
https://imgur.com/XRbXvVl
After:
https://i.imgur.com/mRI1aJq.png (i choose 't' to add a value then type the how many i want to add, in this picture i wanted 1 more value, but i don't get to type my information, it immeadiatly adds random values)
https://imgur.com/HJk1PaW
One major problem: In the fAjouter function you have code like this
n=NbArticle();
nb=n+prods;
for(i=n+1;i<nb;i++)
{
printf("Reference: ");
scanf("%d", &ref[i]);
...
}
The array ref have n elements, and in the loop you start its indexing with n + 1.
Unless prods is equal to zero then i will start out of bounds of the array, and using it as an index will lead to undefined behavior.
Remember that array-size in C is fixed once the array is defined. C doesn't have dynamic arrays. If you need dynamic arrays whose size can be extended you need to use dynamic allocation with e.g. malloc and realloc.
I solved my problem by creating multiple arrays that will take will take the new size and will take the older values and ask the user to enter the new remaining ones.
void fVerifRef(int ref[],int ref2[], int n, int pos)
{
int j,val;
val=ref2[pos];
j=fRecherche2(ref,n,val);
while(j!=-1)
{
printf("Reference deja presente.\n");
printf("Veuillez réessayer: ");
scanf("%d",& ref2[pos]);
val=ref2[pos];
j=fRecherche2(ref,n,val);
if(j==-1)
break;
}
}
int fAjouter(int ref[],int qt[],float prix[],int sds[],int n)
{
int i,nb,prods,code;
printf("Combien de produits voulez vous ajouter:");
scanf("%d",& prods);
fVerifVal(&prods);
n=NbArticle();
nb=n+prods;
int ref2[nb],qt2[nb],sds2[nb];
float prix2[nb];
for(i=0;i<n;i++)
{
ref2[i]=ref[i];
qt2[i]=qt[i];
prix2[i]=prix[i];
sds2[i]=sds[i];
}
for (i=n; i<nb; i++)
{
printf("reference %d : ", i);
scanf("%d", &ref2[i]);
fVerifRef(ref,ref2,n,i);
/*fVerif(ref2,i);*/
printf("quantité %d : ", i);
scanf("%d", &qt2[i]);
fVerif(qt2,i);
printf("Prix %d : ", i);
scanf("%f", &prix2[i]);
fVerifReal(prix2,i);
printf("seuil de sécurité %d : ", i);
scanf("%d", &sds2[i]);
fVerif(sds2,i);
}
fEnregNombre(nb);
code=fEnreg(ref2,qt2,prix2,sds2,nb);
if(code==-1)
return -1;
}
I've started recently to learn how to program in C. I'm following a class online and one of the projects we have to do is create a game where the computer comes up with a random number between two constants, and the user is supposed to find it with the minimal amount of tries possible.
I'm trying to implement a way of counting the tries each time the program passes through the loop (adding +1 to the counter) but all i get is that the number of tries is -472188416 whenever I execute the program as you can see here Program after execution. I don't understand why... Thank you in advance.
Here is the code I made :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int MIN = 1;
int nombreMystere = 0, nombreUser = 0, continuerPartie = 1, MAX = 0, Niveau = 0;
srand(time(NULL));
int compteurCoups = 1;
do
{
printf("Bienvenue qu jeu du numero mystere\n");
printf("Trouvez le bon numero en un minimum de coups\n\n");
printf("Tapez 1 pour le mode facile\n");
printf("Tapez 2 pour le mode moyen\n");
printf("tapez 3 pour le mode difficile\n");
switch(Niveau)
{
case 1:
MAX = 10;
nombreMystere = (rand() % (MAX - MIN + 1)) + MIN;
case 2:
MAX = 100;
nombreMystere = (rand() % (MAX - MIN + 1)) + MIN;
case 3:
MAX = 1000;
nombreMystere = (rand() % (MAX - MIN + 1)) + MIN;
default:
printf("Veuillez introduire un nombre entre 1 et 3 : ");
scanf("%d", &Niveau);
break;
}
do
{
printf("Quel est le nombre ? ");
scanf("%d", &nombreUser);
if (nombreUser > nombreMystere)
{
printf("C'est moins !\n");
nombreUser++;
}
else if (nombreUser < nombreMystere)
{
printf("C'est plus !\n");
nombreUser++;
}
else
{
printf("Bravo, vous avez trouve le nombre mystere en %d essais !!!\n"), compteurCoups;
printf("Voulez vous rejouer ?\n");
printf("Si oui appuyer sur 1, sinon si vous voulez quitter appuyez sur 2\n");
scanf("%d", &continuerPartie);
printf("\n");
}
}while (nombreUser != nombreMystere);
}while (continuerPartie == 1);
return 0;
}
You increase nombreuser in stead of compteurCoups.
It's a syntax error :
printf("Bravo, vous avez trouve le nombre mystere en %d essais !!!\n"), compteurCoups;
Should be
printf("Bravo, vous avez trouve le nombre mystere en %d essais !!!\n", compteurCoups);
Don't forget that "compteurCoups" is an argument of the printf function. Thus, it belongs between the parenthesis after the function name.
I can't find the mistake on the do-while. The loop keeps going if I answer 'N' to the question.(The app is for finding the average of height of an uncertain number of people).
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv) {
int i;
float measure[i],sum,average;
char sex;
char yn;
do{
for(i=1;i;i++) {
printf("Persoa %d",i);
printf("\nIndique se é home (H) ou muller (M): ");
scanf("%s",&sex);
while((sex != 'M') && (sex != 'H'))
{
printf("Lo ha escrito mal.");
printf("\nIndique se é home (H) ou muller (M): ");
scanf("%s",&sex);
}
printf("Indique a súa measure (en metros): ");
scanf("%f",&measure[i]);
sum=sum+measure[i];
printf("\nDesea seguir? (Y/N): ");
scanf("%s",&yn);
while((yn != 'Y') && (yn != 'N'))
{
printf("Lo ha escrito mal.");
printf("\nDesea seguir? (Y/N): ");
scanf("%s",&yn);
}
}
}while(yn == 'Y');
average=sum/i;
printf("\nA media de measures é: %f m.",average);
return (EXIT_SUCCESS);
Need help guys. I need to send this to my teacher tomorrow. I'm a noob on this language :(
two main errors are:
the most critical is:
float measure[i];
you have to declare exactly the size of the table eg:
float measure[50];
the second is: scanf string format for char is "%c" not "%s"
still other error exists.
try this correction to your program
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
#define NB_MESURES 50
int main(int argc, char** argv) {
int i=0;
float measure[NB_MESURES] /* NB_MESURES is predefined to be 50*/
,sum=0,average=0;
char sex=0;
char yn=0;
while(1){ /*endless loop (1)*/
printf("Persoa %d",i);
printf("\nIndique se é home (H) ou muller (M): ");
while(1) /*endless loop (level 2)*/
{
scanf(" %c",&sex);
if((sex == 'M') || (sex == 'H')) break; /*Upper case*/
if((sex == 'm') || (sex == 'h')) break; /*Lower case*/
/* ok exit loop (level 2)
else show the help message */
printf("Lo ha escrito mal.");
printf("\nIndique se é home (H) ou muller (M): ");
}
printf("Indique a súa measure (en metros): ");
scanf("%f",&measure[i]);
sum=sum+measure[i];
i++;
if(i==NB_MESURES){
/*
we can not add more than 50 elements
exiting loop (1)
*/
printf("\nMax Allowed entries is %d\n",NB_MESURES);
break;
}else{
printf("\nDesea seguir? (Y/N): ");
while(1) /* loop (level 2) */
{
scanf(" %c",&yn);
if((yn == 'Y') || (yn == 'N')) break;
if((yn == 'y') || (yn == 'n')) break;
/* if the input was different than ['Y','y','N','n']
show newt message else we break and use yn in the next check to exit loop (level 1)
*/
printf("Lo ha escrito mal.");
printf("\nDesea seguir? (Y/N): ");
}
if((yn == 'N') || (yn == 'n')) break; /*Exit level 1*/
}
}
average=sum/i;
printf("\nA media de measures é: %f m.\n",average);
return (EXIT_SUCCESS);
}
I have a little problem, my program works well until it arrives to the final step, a scanf which asks for continuation of the loop. The problem is that this scan isn't working, but the following system("cls") works. Looks like javascript when async.
Here is the code.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char elegir_dificultad;
int dificil = 1;
printf("Desea que se le indique si el numero es menor o mayor? \n s/n \n");
scanf("%c",&elegir_dificultad);
if(elegir_dificultad == 's'){
dificil = 0;
}
while(1){
int aleatorio, cont, introducido;
cont = 1;
aleatorio = rand()%101;
printf("%d",aleatorio);
int fallo = 1;
while(fallo){
printf("Introduce el numero, intento numero %d \n", cont);
scanf("%d",&introducido);
if(introducido == aleatorio){
fallo = 0;
}
if(cont == 10){
break;
}
if(!dificil){
if(introducido < aleatorio){
printf("El numero introducido es menor que el aleatorio \n");
}
if(introducido > aleatorio){
printf("El numero introducido es mayor que el aleatorio \n");
}
}
if(fallo){
cont++;
}
}
char continuar;
if(fallo){
printf("Has perdido... el numero era %d \n Quieres repetirlo? s/n \n",aleatorio);
scanf("%c",&continuar);
if(continuar=='n'){
break;
}
system("cls");
}else{
printf("°Has ganado! el numero era %d \n Quieres repetirlo? s/n \n",aleatorio);
scanf("%c",&continuar);
if(continuar=='n'){
break;
}
system("cls");
}
}
system("PAUSE");
return 0;
}
This problem is because of \n character left behind by the previous scanf. Place a space before each %c specifier in scanf to eat up \n. .
scanf(" %c", &introducido);
...
scanf(" %c",&continuar);