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.
Related
I have to save three different strings in n number of 2D arrays, for that reason I created a 3D array named datosCliente[size][4][size]. After that I have to print their content. But when I'm printing the strings in the first and second string the first character disappear, and the third string isn't printed.
The first string is the name of a country.
The second is the date of departure.
The last is the date of return.
This is the code:
#include <stdio.h>
#include <stdlib.h>
const int size = 100;
void ingresoDatos(char [size][4][size], int*);
void imprimirDatos(char [size][4][size], int*);
int main(void) {
char datosCliente[size][4][size];
int cant;
FILE *document;
document = fopen("data.txt", "a");
if(document == NULL) {
printf("Error al abrir el archivo.\n");
}else {
ingresoDatos(datosCliente, &cant);
imprimirDatos(datosCliente, &cant);
}
fclose(document);
return 0;
}
void ingresoDatos(char datos[size][4][size], int *cant) {
int tam = 0;
system("clear");
printf("Ingreso de datos\n");
do {
printf("Ingrese el número de clientes: ");
scanf("%d", &tam);
}while(tam >= 100 || tam <= 0);
*cant = tam;
for(int i = 1; i <= tam; i++) {
system("clear");
printf("Ingrese el destino: ");
fgets(&datos[i][0][0], 20, stdin);
getchar();
printf("Ingrese la fecha de salida: ");
fgets(&datos[i][1][0], 30, stdin);
getchar();
printf("Ingrese la fecha regreso: ");
fgets(&datos[i][2][0], 30, stdin);
getchar();
}
}
void imprimirDatos(char datos[size][4][size], int *cant) {
system("clear");
for(int i = 1; i <= *cant; i++) {
printf("Cliente %d:\n", i+1);
printf("Destino: %s", &datos[i][0][100]);
printf("Fecha de salida: %s", &datos[i][1][100]);
printf("Fecha de regreso: %s", &datos[i][2][100]);
printf("\n");
}
}
I enter this data:
tam: 1
Destino (to): China
Fecha de salida (depart in): 23 de septiembre de 2022
Fecha de regreso (return in): 24 de noviembre de 2022
And this is the output:
Cliente 1:
Destino: hina
Fecha de salida: 3 de septiembre de 2022
Fecha de regreso:
I had forgotten mention but I'm using Replit to do the code.
scanf("%d", &tam); doesn't consume a newline character even if it is entered. (c - fgets doesn't work after scanf - Stack Overflow) In my opinion, you shouldn't mix scanf() and fgets(). You can use fgets() to read a line and sscanf() to parse the line.
fgets() consumes a newline character (if it is entered). Calling getchar(); after that will drop the first character of the next line.
Considering these points, the function ingresoDatos should be:
void ingresoDatos(char datos[size][4][size], int *cant) {
int tam = 0;
system("clear");
printf("Ingreso de datos\n");
do {
char buffer[100];
printf("Ingrese el número de clientes: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &tam);
}while(tam >= 100 || tam <= 0);
*cant = tam;
for(int i = 1; i <= tam; i++) {
system("clear");
printf("Ingrese el destino: ");
fgets(&datos[i][0][0], 20, stdin);
printf("Ingrese la fecha de salida: ");
fgets(&datos[i][1][0], 30, stdin);
printf("Ingrese la fecha regreso: ");
fgets(&datos[i][2][0], 30, stdin);
}
}
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;
}
im facing one strange scenario when the output of my function return a ENORMOUS int (4225528), when im trying to sum simple values in a var and return that var to store in a struct.
Whats hapenning ? I tried a simple pointer func that i saw here, didnt work, heres my code, anyone has idea how to solve this ?
The function is "int cadastrarPedido(int Cad);"
Executable : https://repl.it/#thzmendes/UnwrittenHorizontalStructs
Here is where i call and the func
#include <stdio.h>
int cadastroPedido(int Cad);
int main(void) {
printf("Voce selecionou a opcao 4 - Cadastrar Pedido\n");
int Cad;
int vlr_T=0;
printf("\nDigite numero do cadastro: ");
scanf("%d",&Cad);
vlr_T = cadastroPedido(Cad);
printf("\n Valor total : %d",&vlr_T);
return 0;
}
int cadastroPedido(int Cad){
int Option;
int OpcaoPedido;
int valor=0;
if(Cad>0)
{
do
{
printf("\nEscolha o seu pedido: ");
printf("\n1- Pizza de Calabresa -50 reais");
printf("\n2- Pizza de Frango - 40 reais");
printf("\n2- Pizza de Mussarela - 30 reais");
printf("\n2- Coca Cola- 10 reais");
printf("\n2- Guarana- 10 reais");
scanf("%d", &OpcaoPedido);
if(OpcaoPedido == 1)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
valor +=50;
scanf("%d", &Option);
}
else
if(OpcaoPedido == 2)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
scanf("%d", &Option);
valor +=40;
}
else
if(OpcaoPedido == 3)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
scanf("%d", &Option);
valor +=30;
}
else
if(OpcaoPedido == 4)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
scanf("%d", &Option);
valor +=10;
}
else
if(OpcaoPedido == 5)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
scanf("%d", &Option);
valor +=10;
}
}while(Option == 1);
}
return valor;
}
I've slapped your code a little bit. This code snippet was enough to reproduce your "bug".
#include <stdio.h>
int cadastroPedido(int Cad);
int main(void) {
int valor = cadastroPedido(1);
printf("%d",valor);
return 0;
}
int cadastroPedido(int Cad){
int Option;
int OpcaoPedido;
int valor;
if(1==Cad)
{
do
{
printf("\nEscolha o seu pedido: ");
printf("\n1- Pizza de Calabresa -50 reais");
printf("\n2- Pizza de Frango - 40 reais");
scanf("%d", &OpcaoPedido);
if(OpcaoPedido == 1)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
valor +=50;
scanf("%d", &Option);
}
else
if(OpcaoPedido == 2)
{
printf("\nPressione 1 para continuar pedindo ou 2 para volar ao menu principal: ");
scanf("%d", &Option);
valor +=40;
}
}while(Option == 1);
}
return valor;
}
You'll see that the local variable of cadastroPedido valor is uninitialized when the function is called. This means that the program will pick a position in memory. Due to RAM shenanigans, that position in memory may have a random value already in it.
You can avoid this by explicitly declaring it like int value = 0, so you will always know the starting value of that variable and so that you aren't at the mercy of preexisting memory states.
If you don't initialize variables when you declare them in C, you're at risk of tripping into these inconsistencies, specially during += operations.
First at all english its not my first language i will try my best.
Hello guys, I have a problem i'm trying to delete a determinate position of the struct, so instead of deleting the info inside by modifying the string with strcpy or just setting the int or float to 0 i want to erase the data in the struct by changing the position with the next one so 1.2.3.4.5 will be 1.2<-3.4.5 and stay this way 1.2.3.4, problem is after 1h trying to make it works there are some problems, first: if there's only one student after the program ask me for the id to erase, the new id seems to be a random number or like garbage data, so i guess the position changed but the data inside of this id persist.
Example:
id: 1
name: john
lastname: smith
score1: 2
score2: 5
score3: 6
After the function ask me for the id to be erased:
id: 425262
name: john
lastname: smith
score1: 2
score2: 5
score3: 6
the second issue is, if i insert some students, and the program ask for the id to be erased, all id numbers changes to that id i just insert instead of deleting the id target.
Heres the full code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct alumnos{
int id;
char alumno[10];
char apellido[15];
float nota1;
float nota2;
float nota3;
};
int insertar_notas(struct alumnos notas[20],int n,int *id_alumno);
void mostrar_notas(struct alumnos notas[20],int n);
void buscar_alumno(struct alumnos notas[20],int n);
void cambiar_notas(struct alumnos notas[20],int n);
void eliminar_alumno(struct alumnos notas[20],int n);
int main (void){
int menu = 0, n = 0, id_alumno = 1;
struct alumnos notas[20];
puts("\n<><><>Bienvenido al recuento de notas de la escuela<><><>\n");
puts("\nQue deseas hacer?\n");
while (menu != 6){
puts("\n1)Insertas las notas de un alumno\n2)Ver todas las notas\n3)Ver las notas de un alumno\n4)Modificar notas\n5)Eliminar datos del alumno\n6)Salir\n");
scanf("%d", &menu);
switch(menu){
case 1:
n=insertar_notas(notas,n,&id_alumno);
break;
case 2:
mostrar_notas(notas,n);
break;
case 3:
buscar_alumno(notas,n);
break;
case 4:
cambiar_notas(notas,n);
break;
case 5:
eliminar_alumno(notas,n);
break;
}
}
}
int insertar_notas(struct alumnos notas[20], int n,int *id_alumno){
char resp[3];
system("cls");
puts("\n \a Insercion del alumno\n");
while (!strstr(resp,"no")){
fflush(stdin);
printf("\nEl ID de este alumno sera: %d\n", *id_alumno);
notas[n].id=*id_alumno;
(*id_alumno)++;
puts("\nDime el nombre del Alumno\n");
scanf("%10s", notas[n].alumno );
system("cls");
fflush(stdin);
puts("\nDime el apellido del Alumno\n");
scanf("%10s", notas[n].apellido );
system("cls");
puts("\nDime la Primera nota trimestral del Alumno[1.23]\n");
scanf("%f", ¬as[n].nota1 );
system("cls");
puts("\nDime la Segunda nota trimestral del Alumno[1.23]\n");
scanf("%f", ¬as[n].nota2 );
system("cls");
puts("\nDime la Tercera nota trimestral del Alumno[1.23]\n");
scanf("%f", ¬as[n].nota3 );
n++;
system("cls");
puts("\nQuieres volver a insertar otro?[si|no]\n");
scanf("%3s", resp);
strlwr(resp);
}
return n;
}
void mostrar_notas(struct alumnos notas[20],int n){
int i;
system("cls");
if (n != 0 ){
puts("\nLos alumnos insertados son:\n");
for (i = 0; i < n; i++)
{
printf("\n\nID %d\n\n Nombre:%s\n Apellido: %s\n Primera nota:%0.2f\n Segunda nota:%0.2f\n Tercera nota:%0.2f\n\n", notas[i].id, notas[i].alumno, notas[i].apellido ,notas[i].nota1 ,notas[i].nota2 ,notas[i].nota3 );
}
}
else
{
puts("\n \aNo hay registro\n");
}
}
void buscar_alumno(struct alumnos notas[20],int n){
int num = 0;
float media;
if (n != 0){
char ape_alumno[15];
system("cls");
puts("\n\aBusqueda por alumno\n");
puts("\nDime el apellido del alumno\n");
scanf("%15s", ape_alumno);
for ( num = 0; num < n ; num++){
if (strcmp(notas[num].apellido,ape_alumno)==0){
printf("\nEl alumno introducido es: %s %s\n", notas[num].alumno, notas[num].apellido );
media=(notas[num].nota1+notas[num].nota2+notas[num].nota3)/3;
printf("\nLa nota media es %0.2f \n", media);
if (media<5){
puts("\nSuspendido no hace media\n");
}
if (media=5 & media>6){
puts("\nSuficiente\n");
}
}
}
}else{
puts("\a\nRegistro vacio\n");
}
}
void cambiar_notas(struct alumnos notas[20],int n){
char ape_notas[15];
float nueva_nota1,nueva_nota2,nueva_nota3,nota_n1t,nota_n2t,nota_n3t;
int j = 0, submenu_mod = 0, nota_mod;
if (n != 0){
system("cls");
puts("\n \aDime el apellido del alumno a modificar las notas\n");
scanf("%15s", ape_notas);
for (j = 0;j < n; j++){
if (strcmp(notas[j].apellido,ape_notas)==0){
printf("\nLas notas de este alumno %s %s son:\n \n1r Trimestre:%0.2f\n \n2n Trimestre:%0.2f\n \n3r Trimestre:%0.2f\n", notas[j].alumno,notas[j].apellido,notas[j].nota1 ,notas[j].nota2 ,notas[j].nota3 );
while(submenu_mod != 3){
puts("\nQue quieres hacer?:\n\n1)Modificar todas las notas\n2)Modificar solo una nota\n3)Salir\n");
scanf("%d", &submenu_mod);
switch(submenu_mod){
case 1:
puts("\nDime la primera nota trimestral\n");
scanf("%f", &nueva_nota1);
puts("\nDime la segunda nota trimestral\n");
scanf("%f", &nueva_nota2);
puts("\nDime la tercera nota trimestral\n");
scanf("%f", &nueva_nota3);
notas[j].nota1=nueva_nota1;
notas[j].nota2=nueva_nota2;
notas[j].nota3=nueva_nota3;
printf("\nLas nuevas notas de este alumno son:\n \n1r Trimestre:%0.2f\n \n2n Trimestre:%0.2f\n \n3r Trimestre:%0.2f\n", notas[j].nota1 ,notas[j].nota2 ,notas[j].nota3 );
system("pause");
break;
case 2:
while (nota_mod != 4){
puts("\nQue nota trimestral quieres modificar?:\n");
printf("\n1)Nota trimestral %0.2f\n2)Nota trimestral %0.2f\n3)Nota trimestral %0.2f\n4)Salir", notas[j].nota1,notas[j].nota2,notas[j].nota3);
scanf("%d", ¬a_mod);
switch(nota_mod){
case 1:
puts("\nDime la nueva nota del Primer trimestre:\n");
scanf("%f", ¬a_n1t);
notas[j].nota1=nota_n1t;
printf("La nueva nota del primer trimestre para el alumno %s %s es: \n%0.2f", notas[j].alumno,notas[j].apellido,notas[j].nota1);
break;
case 2:
puts("\nDime la nueva nota del Segundo trimestre:\n");
scanf("%f", ¬a_n2t);
notas[j].nota2=nota_n2t;
printf("La nueva nota del Segundo trimestre para el alumno %s %s es: \n%0.2f", notas[j].alumno,notas[j].apellido,notas[j].nota2);
break;
case 3:
puts("\nDime la nueva nota del Tercer trimestre:\n");
scanf("%f", ¬a_n3t);
notas[j].nota3=nota_n3t;
printf("La nueva nota del Tercer trimestre para el alumno %s %s es: \n%0.2f", notas[j].alumno,notas[j].apellido,notas[j].nota3);
break;
}
break;
}
}
}
} else {
puts("\nNo se ha encontrado ese apellido\n");
}
}
} else {
system("cls");
puts("\n \aRegistro vacio\n");
}
}
The function:
void eliminar_alumno(struct alumnos notas[20],int n){
int id_eli = 0, r = 0;
mostrar_notas(notas,n);
puts("\nInserta la id del alumno a eliminar\n");
scanf("%d",&id_eli);
for(r = 0;r < n;r++){
if (notas[r].id = id_eli){
notas[r].id=notas[r+1].id;
n--;
}
}
}
Compile with warnings:
if (notas[r].id = id_eli){
should be
if (notas[r].id == id_eli){
Also, this is wrong:
if (media=5 & media>6){
Suficiente = [5 - 6) right? Then you want if (media >= 5 && media < 6)
Try the following changes in your eliminar_alumno function-
for(r = 0;r < n;r++){
if (notas[r].id == id_eli){
for(i=r;i < (n-1);i++)
notas[i]=notas[i+1];
notas[i].id -= 1;
n--;
}
}
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);