|
412
|
Programación / Programación C/C++ / Re: hola a todos y ayuda
|
en: 26 Febrero 2014, 17:20 pm
|
Para cuando postees el código elige las etiquetas GeSHi y toma la C++ y en medio de las etiquetas Code que aparecen "pegas" tu código. Al no hacerlo de esta manera parte del código no sale correcta, especialmente las matrices.#include<stdio.h> #include<stdlib.h> #include<windows.h> #include<conio2.h> int main () { int h=0,m=0,s=0; clrscr(); textcolor (14); for(h=0;h<=24;h++){ clrscr(); for(m=0;m<60;m++){ clrscr(); for(s=0;s<60;s++) { Sleep(1000); gotoxy(37,20); printf(" %d:%d:%d",h,m,s); } } } getch(); return 0; }
No indicas qué problema tienes, ya que a falta del return de main, recuerda que esta es de tipo int, el código parece hacer lo que quieres, un poco descentrado eso sí.¡¡¡¡ Saluditos! ..... !!!!
|
|
|
413
|
Programación / Programación C/C++ / Re: [C] Problema con ejercicio
|
en: 25 Febrero 2014, 19:47 pm
|
Teniendo en cuenta que ya dmacias ha propuesto un código con la condición en el while, "recompongo" mi propuesta del while(1), esta vez con la condición incorporada al mismo, no quiero que por mi culpa se"revuelva"el patio:
#include <stdio.h> int main() { float a = 2.98; float b = 4.50; float c = 9.98; float d = 4.49; float e = 6.87; int n=0; int x = 0; float total=0; float a2=0,b2=0,c2=0,d2=0,e2=0; do{ printf("Ingrese el codigo de producto: 1-5 (-1 para salir): "); scanf("%d", &x); if(x >= 1 && x <= 5){ printf("Ingrese las unidades vendidas: "); scanf("%d", &n); } switch (x){ case 1: a2 += a*n; break; case 2: b2 += b*n; break; case 3: c2 += c*n; break; case 4: d2 += d*n; break; case 5: e2 += e*n; break; default: if (x!=-1) printf("Introdujo un codigo erroneo\n"); break; } /*fin de switch*/ } /*fin de do*/ while (x!=-1); /*condicion de do*/ total = a2+b2+c2+d2+e2; printf("El total vendido es %1.2f \n", total); return 0; }
¡¡¡¡ Saluditos! ..... !!!! P.D: Juraito, juraito que el código está bien indentado, pero no sé que pasa últimamente que al ponerlo en las Code se "desparrama".
|
|
|
414
|
Programación / Programación C/C++ / Re: [C] Problema con ejercicio
|
en: 25 Febrero 2014, 16:19 pm
|
...................................................................... No sabía que se podia hacer esto if (x==-1) break
Solo he visto break en switch, lo desconocia. Y esto no lo entiendowhile (1); /*condicion de do*/
Que es lo que valida esa condicion???? supongo que el 1 solo no será?? Provoca un bucle infinito que se rompe desde el "interior" del mismo, como con el if-break, al cumplirse alguna condición.¡¡¡¡ Saluditos! ..... !!!!
|
|
|
415
|
Programación / Programación C/C++ / Re: [C] Problema con ejercicio
|
en: 25 Febrero 2014, 05:55 am
|
En cualquier caso, inicializando las variables x2 a cero, ya que son sumas parciales, puedes prescindir perfectamente de las x1 sin más que ir haciendo "a2 += a*n;", etc..do{ printf("Ingrese el codigo de producto: 1-5 (-1 para salir): "); scanf("%d", &x); if (x==-1) break; else if(x >= 1 && x <= 5){ printf("Ingrese las unidades vendidas: "); scanf("%d", &n); } switch (x){ case 1: a2 += a*n; break; case 2: b2 += b*n; break; case 3: c2 += c*n; break; case 4: d2 += d*n; break; case 5: e2 += e*n; break; default: printf("Introdujo un codigo erroneo\n"); break; } /*fin de switch*/ } /*fin de do*/ while (1); /*condicion de do*/
¡¡¡¡ Saluditos! ..... !!!!
|
|
|
416
|
Programación / Programación C/C++ / Re: Funcion recursiva
|
en: 19 Febrero 2014, 19:50 pm
|
¿Y cómo le hago para que en vez de arrojarme el resultado, me arroje el procedimiento del factorial paso por paso? Es para dar a entender al que ve el resultado en pantalla cómo funciona el factorial de un numero.
Ingresa un numero del cual desees obtener su factorial: 8
El factorial de 8 es: 8! = 8*7*6*5*4*3*2*1 = 40320 Presione una tecla para continuar . . .
Aporta qué diablos calcula factorial para alguien que no lo sepa:#include <stdio.h> int factorial(int n) { if(n<=1){ printf("1"); return 1; } else if(n>1){ printf("%d*",n); return n*factorial(n-1); } } int main(){ int n; printf("Ingresa un numero del cual desees obtener su factorial: "); scanf("%d",&n); if(n<0){ printf("El numero ha de ser mayor o igual a cero"); return 1; } printf("\nEl factorial de %d es: %d! = ",n,n); printf(" = %d\n", factorial(n)); return 0; }
¡¡¡¡ Saluditos! ..... !!!!
|
|
|
417
|
Programación / Programación C/C++ / Re: Busqueda de valores con matrices
|
en: 15 Febrero 2014, 15:17 pm
|
Antes que nada cuando postees código elige las etiquetas GeSHi y toma la C++ y en medio de las etiquetas Code que aparecen "pegas" tu código. Al no hacerlo de esta manera parte del código no sale correcta, especialmente las matrices. Este es tu código con etiquetas:#include <stdio.h> #define MAXFIL 9 #define MAXCOL 9 void buscarVerti(int matriz[MAXFIL][MAXCOL],int *puntos){ int contador=1; int i,j; for (j=0;j<MAXCOL;j++){ for (i=0;i<7;i++){ if (matriz [i ][j]==matriz[i+1][j]){ contador++; } else if (matriz [i][j] !=matriz[i+1][j]){ contador=1; } if (contador==3 && i<7 && (matriz[i+1][j]==matriz[i+2][j])){ printf("\n\n ENCONTRO 4 CARAMELOS EN LA COLUMNA: %d DESDE LA FILA %d A LA FILA %d \n",j+1,i,i+3); puntosN1=puntosN1+7; matriz [i ][j]=1+(rand()%5); matriz[i+1][j]=1+(rand()%5); matriz[i+2][j]=1+(rand()%5); matriz[i+3][j]=1+(rand()%5); break; } else if (contador==3 && i<8 && (matriz[i][j]==matriz[i+1][j]) ){ printf("\n\n ENCONTRO 3 CARAMELOS EN LA COLUMNA: %d DESDE LA FILA %d A LA FILA %d \n",j+1,i,i+2); puntosN1=puntosN1+5; matriz[ i] [j]=1+(rand()%5); matriz[i+1][j]=1+(rand()%5); matriz[i+2][j]=1+(rand()%5); break; } } } } void buscarHori(int matriz[MAXFIL][MAXCOL],int *puntos){ int contador=1; int i,j; for(i=0;i<MAXFIL;i++){ for(j=0;j<7;j++){ if (matriz[i][j]== matriz[i][j+1]) contador=contador+1; puntosN1=puntosN1; if (matriz[i][j]!=matriz[i][j+1]) contador=1; puntosN1=puntosN1; if (contador==3 && j<7 && (matriz[i][j+1]==matriz[i][j+2])){ printf("\n\n ENCONTRO 4 CARAMELOS DESDE LA COLUMNA: %d HASTA LA COLUMNA %d EN LA FILA %d \n",j,j+3,i+1); matriz[i][j]=1+(rand()%5); matriz[i][j+1]=1+(rand()%5); matriz[i][j+2]=1+(rand()%5); matriz[i][j+3]=1+(rand()%5); puntosN1=puntosN1+7; break; } if (contador==3 && j<8 && (matriz[i][j]==matriz[i][j+1])){ printf("\n\n ENCONTRO 3 CARAMELOS DESDE LA COLUMNA: %d HASTA LA COLUMNA %d EN LA FILA %d \n",j,j+2,i+1); puntosN1=puntosN1+5; matriz[i][j]=1+(rand()%5); matriz[i][j+1]=1+(rand()%5); matriz[i][j+2]=1+(rand()%5); break; } } } } int main(){ int i,j; int *puntos=0; int matriz[MAXFIL][MAXCOL]; for (i=0;i<MAXFIL;i++){ for(j=0;j<MAXCOL;j++){ matriz[i][j]=1+rand()%5 printf("%i",matriz[i][j]); } printf("\n"); } buscarCaramelosVertical (matriz,puntosN1); buscarCaramelosHorizontal (matriz,puntosN1); printf("Ud tiene %i puntos",puntosN1); }
¡¡¡¡ Saluditos! ..... !!!! P.D: Revisa y corrige un poco el código ya que ni compila.
* Para empezar falta un punto y coma en una línea de main :
matriz[i][j]=1+rand()%5
* Te falta el return de la función main.
*¿ Qué sentido tiene?:
if (contador==3 && j<7 ......
En lugar de usar:if (contador==3 && j<MAXCOL-2
* Llamas a las funciones con unos nombres y las invocas con otros.
* Tomas como uno de los argumentos de las funciones al invocarlas a la variable puntosN1 que no tienes declarada en main, ni falta que te hace.
Más bien sería:int main(){ int i,j; int puntos=0; int matriz[MAXFIL][MAXCOL]; for (i=0;i<MAXFIL;i++){ for(j=0;j<MAXCOL;j++){ matriz[i][j]=1+rand()%5; printf("%i",matriz[i][j]); } printf("\n"); } buscarHori(matriz,&puntos); return 0; } .................................... void buscarHori(int matriz[MAXFIL][MAXCOL],int *puntosN1){ ..........................................
Y lo mismo con la otra función.
* ¿Qué sentido tiene:puntosN1=puntosN1;
Ya sabemos que una variable es igual a si misma.
* etc, etc. Vete arreglando esas cositas y vuelve a postear el avance y especifica de forma concreta qué problemas te surgen.¡¡¡¡ Saluditos! .....Otra vez !!!! P.d de P.D: ¿De verdad has hecho tú el código?. Si es así sólo tienes que fijarte un poquito más en lo que pones, porque lo de llamar a las funciones de forma diferente que al invocarlas me parece una pasada de error trivial.
|
|
|
418
|
Programación / Programación C/C++ / Re: Modulo distinguir letras de numeros
|
en: 15 Febrero 2014, 05:43 am
|
PD: ¿Cómo hacéis para que el código os salga en colores en el foro?
Elige las etiquetas de C++ en lugar de las de C.
Lo de las opciones ya funciona, aunque creo que te faltan por implementar otras funciones:#include <iostream> #include <vector> #include <fstream> #include <cstdlib> #include <cstring> using namespace std; typedef struct { int id; // El identificador de una nueva cancion debe ser igual a idNextSong string title; string artist; string album; string genre; string url; } Song; typedef struct { vector<Song> songs; int idNextSong; // Cada vez que se anyada una cancion a la coleccion, incrementar idNextSong } Collection; // Función para inicializar los valores de la colección Collection createCollection(); //rellenar datos cancion Song demandSong(); //comprobar cancion bool isSongInCollection(const Collection &collection, Song song); //añadir cancion bool addSong(Collection &collection); //imprimir canciones void printSong(Song song); //buscar y mostrar canciones bool showCollection(const Collection &collection); //encontrar ir int findIdSong(const Collection &collection, int id); //editar la cancion void editSong(Collection &collection); //borrar la cancion void deleteSong(Collection &collection); //prueba bool Comprobarnumero(int numero); // Implementar resto de funciones int main() { Collection collection=createCollection(); char opcion[10]; int longitud=0; do{ cout<<"--------------------------------"<<endl; cout<<"----------- MiniTunes ----------"<<endl; cout<<"--------------------------------"<<endl; cout<<"1- Add song"<<endl; cout<<"2- Edit song"<<endl; cout<<"3- Delete song"<<endl; cout<<"4- Show collection"<<endl; cout<<"5- Manage playlist"<<endl; cout<<"6- Import iTunes JSON data"<<endl; cout<<"7- Export playlist to XSPF"<<endl; cout<<"8- Save data"<<endl; cout<<"9- Load data"<<endl; cout<<"0- Play playlist"<<endl; cout<<"q- Quit"<<endl; cout<<"Option: "; cin>>opcion; cin.get(); longitud=strlen(opcion); if (longitud>=2 ) opcion[0]='a'; if (opcion[0]!='1' && opcion[0]!='2' && opcion[0]!='3' && opcion[0]!='4' && opcion[0]!='5' && opcion[0]!='6' && opcion[0]!='7' && opcion[0]!='8' && opcion[0]!='9' && opcion[0]!='0' && opcion[0]!='q'){ cout<<"Error: Unknown option"<<endl; } switch (opcion[0]){ case '1': addSong(collection); break; case '2': editSong(collection); break; case '3': deleteSong(collection); break; case '4': showCollection(collection); break; } }while(opcion[0]!='q'); return 0; } Collection createCollection() { Collection collection; collection.idNextSong=1; return collection; } Song demandSong(){ Song song; cout<<"Title: "; getline(cin, song.title); cout<<"Artist: "; getline(cin, song.artist); cout<<"Album: "; getline(cin, song.album); cout<<"Genre: "; getline(cin,song.genre); cout<<"Url: "; getline(cin, song.url); return song; } bool isSongInCollection(const Collection &collection, Song song){ bool repetida=false; unsigned int i; for(i=0;i<collection.songs.size() && !repetida;i++){ if(song.title==collection.songs[i].title && collection.songs[i].artist==song.artist){ repetida=true; } } return repetida; } bool addSong(Collection &collection){ bool repetida; Song song=demandSong(); repetida=isSongInCollection(collection, song); if (repetida==true){ cout<<"The song "<<song.title<<" is already in the collection"<<endl; } else { song.id=collection.idNextSong; collection.songs.push_back(song); collection.idNextSong++; } return repetida; } void printSong(Song song){ cout<<song.id<<" | "<<song.title<<" | "<<song.artist<<" | "<<song.album<<" | "<<song.genre<<endl; } bool showCollection(const Collection &collection){ string buscado; bool encontrado; int aux=0; cout<<"Search: "<<endl; getline(cin, buscado); for(unsigned int i=0;i<collection.songs.size();i++){ encontrado=false; if (collection.songs[i].title.find(buscado)!=string::npos){ encontrado=true; } else if(collection.songs[i].artist.find(buscado)!=string::npos){ encontrado=true; } else if(collection.songs[i].album.find(buscado)!=string::npos){ encontrado=true; } else if(collection.songs[i].genre.find(buscado)!=string::npos){ encontrado=true; } if (encontrado==true){ printSong(collection.songs[i]); aux++; } } if(aux==0){ cout<<"No results"<<endl; } return encontrado; } int findIdSong(const Collection &collection, int id){ int encontrado=-1; for(unsigned int k=0;k<=collection.songs.size();k++){ if(id==collection.songs[k].id){ encontrado=k+1; } } return encontrado; } void editSong(Collection &collection){ int encontrado, eleccion, buscado,aux=0;; for(unsigned int i=0;i<collection.songs.size();i++){ printSong(collection.songs[i]); } char buscado_char[100]; cout<<"Select song:"<<endl; cin>>buscado_char; for (int i=0;buscado_char[i];i++){ aux++; if (buscado_char[i]<'0' || buscado_char[i]>'9'){ break; } } if (strlen(buscado_char)==aux){ buscado=atoi(buscado_char); encontrado=findIdSong(collection, buscado); if(aux==2){ cout<<"Error: Unknown song "<<buscado<<endl; } else{ do{ cout<<"Edit (1-Title, 2-Artist, 3-Album, 4-Genre, 5-Url):"<<endl; cin>>eleccion; cin.get(); switch(eleccion){ case 1: cout<<"Title: "; getline(cin, collection.songs[buscado-1].title); break; case 2: cout<<"Artist: "; getline(cin, collection.songs[buscado-1].artist); break; case 3: cout<<"Album: "; getline(cin, collection.songs[buscado-1].album); break; case 4: cout<<"Genre: "; getline(cin, collection.songs[buscado-1].genre); break; case 5: cout<<"Url: "; getline(cin, collection.songs[buscado-1].url); break; default: cout<<"Error: Unknow option"<<endl; break; } }while(eleccion!=1 && eleccion!=2 && eleccion!=3 && eleccion!=4 && eleccion!=5); } } else{ //si no es un numero mostrar este mensaje de error y vovler a mostrar el menu cout<<"No results"<<endl; } } void deleteSong(Collection &collection){ int buscado_del, encontrado3=0; char sino; for(unsigned int i=0;i<collection.songs.size();i++){ printSong(collection.songs[i]); } cout<<"Select song: "<<endl; cin>>buscado_del; encontrado3=findIdSong(collection, buscado_del); if(encontrado3==-1){ cout<<"Error: Unknown song "<<buscado_del<<endl; } else{ cout<<"Delete "<<collection.songs[buscado_del-1].id<<" | "<<collection.songs[buscado_del-1].title<<" | "; cout<<collection.songs[buscado_del-1].artist<<" | "<<collection.songs[buscado_del-1].album<<" | "<<collection.songs[buscado_del-1].genre<<"? (Y/N)"<<endl; cin>>sino; cin.get(); if(sino=='N'){ cout<<"Song not deleted"<<endl; } else{ collection.songs.erase(collection.songs.begin()+buscado_del-1); } } } /********** FUNCION COMPRUEBA ENTERO *************/ int comprobar_cadena_como_numero (char cadena[100]){ for (int i=0;cadena[i];i++){ if (cadena[i]<'0' || cadena[i]>'9'){ return 1; } } return 2; } /********************************************************/
¡¡¡¡ Saluditos! ..... !!!!
|
|
|
419
|
Programación / Programación C/C++ / Re: modificacion codigo ???
|
en: 14 Febrero 2014, 21:25 pm
|
Y si sólo se quieren las diferencias entre líneas sucesivas, tipo: 4 5 2 10 14 6 -6 -4 -4 -5-14-15 4 -4 -8-10 -6 3 2 3 11 7 13 -3 2 4 1 6 7 23 1 3 3 4 -2-17 -3 0 -7-16-16 -6 3 2 5 15 15 17 -3 -7 0 -6 0 0
#include <stdio.h> #include <stdlib.h> int main() { int i=0,j=0,k=0,y[2][6]; FILE* fichero,*fich; fichero = fopen("combiLuis0.txt", "r"); if ((fichero = fopen("combiLuis0.txt", "r")) == NULL){ perror("combiLuis0.txt"); return EXIT_FAILURE; } fich = fopen("CombiDiferanciasLuis01.txt", "w"); if ((fich = fopen("CombiDiferanciasLuis01.txt", "w")) == NULL){ perror("CombiDiferanciasLuis01.txt"); return EXIT_FAILURE; } i = 0; while (fscanf(fichero,"%d %d %d %d %d %d ", &y[i][0], &y[i][1], &y[i][2], &y[i][3], &y[i][4], &y[i][5] )==6){ i++;k++; if (i>1){ printf("\n"); fprintf(fich,"\n"); for (j=0;j<6;j++){ printf ("%3i",y[0][j]-y[1][j]); fprintf (fich,"%3i",y[0][j]-y[1][j]); } for (j=0;j<6;j++) y[0][j]=y[1][j]; i=1; } } fclose(fichero); fclose(fich); return EXIT_SUCCESS; }
¡¡¡¡ Saluditos! ..... !!!!
|
|
|
|
|
|
|