i made a program to calculate multiples of 5 between two numbers, when ask for de second numbers the program didn't work normally.
#include <stdio.h>
int main()
{
int A, B, cont;
printf("\n");
printf("Indique el dominio de los numeros en los que desa saber cuales son multiplos de 5\n");
printf("Primer numero: \n");
scanf("%i",&A);
printf("Segundo numero: \n");
scanf("%i",&B);
if (A < B){
A = B;
//B = A;
}
system("cls");
printf("\n");
printf("Los multiplos de 5 comprendidos entre %i y %i son; \n",A,B);
cont = 0;
while(A < B){
if (A % 5 == 0)
cont++;
A++;
}
if (cont > 0)
printf("Entre los numeros %i y %i hay un total de %i multiplos de 5.\n",A,B,cont);
else
printf("El intervalo no se encuentran multiplos de 5.\n");
getchar();
return 0;
}
You have the format backwards
scanf("i%",&A);
should be
scanf("%i",&A);
Your swapping logic is wrong. Use another variable to do it correctly.
int t = A;
A = B;
B = t;
Also you would want to swap when A is greater than B.
if( A > B ){
/* swap*/
}
#include <stdio.h>
int main()
{
int A, B, cont=0;
printf("Program to find the Multiples of 5\n");
printf("First Number \n");
scanf("%d",&A);
printf("Second Number \n");
scanf("%d",&B);
system("cls");
printf("The Multiples of 5 between %d and %d \n", A,B);
if(A<B){
while(A <= B){
if (A % 5 == 0)
{
cont++;
}
A++;
}
}
else
{
while(A >=B){
if (A % 5 == 0)
{
cont++;
}
A--;
}
}
if (cont > 0)
printf("The total Multiples of 5 between %d and %d are %d\n",A,B,cont);
else
printf("No Multiple of 5 exists between %d and %d\n",A,B);
getchar();
return 0;
}
I try to solve each case. If user enter A>B then your code fails but it works
Related
I want to make a program that returns the average of the numbers entered but i get this error:
incompatible types when assigning to type ‘float *’ from type ‘float’
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float* promedio (float *dataPtr, int dataCant)
{
float *p;
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
*dataPtr +=1;
}
p = total / dataCant;
return (p);
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i++;
}
q = promedio (&v[0], i);
printf ("El promedio vale %f\r\n", *q);
free (v);
return (0);
}
Your approach of returning a pointer from promedio doesn't make much sens.
You probably want this:
void promedio (float *dataPtr, int dataCant, float *result)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1; // remove the *, you want to increment the pointer
} // not the thing it points to
*result = total / dataCant;
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i++;
}
float q;
promedio (&v[0], i); // you should write `v` innstead of the cumbersome `&v[0]`
printf ("El promedio vale %f\r\n", q); // q is a float, removge the *
// remove free (v), you can only free stuff allocated via malloc and friends
return (0);
}
Anyway, I have the strong impression you should read again the chapter dealing with pointers in your learning material.
It turns out you rather need this:
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1; // remove the *, you want to increment the pointer
} // not the thing it points to
return = total / dataCant;
}
#Jabberwocky
Thank you for your answer, thanks it I managed to solve the exercise. This is the answer (works)
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1;
}
return (total / dataCant);
}
int main (void)
{
float v[CANT], q, a;
int i=0;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) && (a != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &a);
if (a != -1) {
v[i]=a;
i++;
}
}
q = promedio (&v[0], i);
printf ("El promedio vale %0.2f\r\n", q);
return (0);
}
I hope this will be the last time I ask something here. Everything in my Food Ordering Algorithm is finished, but showing the list of filled orders shows every slot available (0 to 100), rather than just the entries filled out. Any way to fix that?
Case 3: Shows all orders made. (But I want just the entries that are filled out, not the empty ones.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAM 100
typedef struct order
{
char nome[50];
char endereco[150];
char pedido[300];
char valor[10];
};
int main()
{
struct order lista[TAM];
int busca, acha, i, menu;
i = 0;
menu = 0;
int codigo = 0;
int c = 0;
while(menu != 4)
{
system("cls");
printf("====================\n");
printf("Selecione uma opcao\n");
printf("====================\n");
printf("1 - Cadastrar pedido\n");
printf("2 - Consultar pedido\n");
printf("3 - Emitir relatorio\n");
printf("4 - Sair\n");
scanf("%d", &menu);
fflush(stdin);
switch(menu)
{
case 1:
system("cls");
printf("Digite seu nome: \n");
scanf("%49[^\n]", lista[i].nome);
fflush(stdin);
printf("Digite seu endereco: \n");
scanf("%149[^\n]", lista[i].endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
scanf("%299[^\n]", lista[i].pedido);
fflush(stdin);
printf("Digite o valor total: \n");
scanf("%9[^\n]", lista[i].valor);
fflush(stdin);
system("cls");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
system("pause");
i = i + 1;
codigo = codigo + 1;
break;
case 2:
system("cls");
printf("Insira o codigo que deseja buscar:\n");
scanf("%d", &busca);
fflush(stdin);
if(busca < codigo)
{
printf("=============================\n");
printf("Codigo: %d\n", busca);
printf("Nome: %s\n", lista[busca].nome);
printf("Endereco: %s\n", lista[busca].endereco);
printf("Pedido: %s\n", lista[busca].pedido);
printf("Valor total: %s\n", lista[busca].valor);
printf("=============================\n");
system("pause");
}
else
{
printf("\n Codigo nao encontrado\n");
system("pause");
break;
}
break;
case 3:
system("cls");
c = 0;
for(i = 0; i < TAM; i++){
printf("=============================\n");
printf("Codigo: %d\n", c);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
c = c + 1;
}
system("pause");
break;
case 4:
return 0;
default:
printf("Opcao invalido\n");
system("pause");
}
}
return 0;
}
change
for(i = 0; i < TAM; i++){
to
for(i = 0; i < codigo ; i++){
codigo is the count og entrries, TAM is the max number of entries
So, I've made this code, and it works wonderfully, but the problem is that I've got some scanf functions only accepting numbers, and some others only accepting characters, but for example, when I input a character on a scanf that requires an int value, the program behaves really unexpectedly, doing stuff such as repeating the same printf all over the command prompt, or repeating it thrice.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int descuento(int num, int descuento);
int rangoValido(int Rangomin, int Rangomax, int i);
int numeroRandom();
int sino(char sino);
int main(void){
int productoid[1000][1];
int idprompt;
int descuento25[14] = {398, 309, 281, 948, 19, 67, 187, 80, 889, 482, 566, 24, 87, 98};
int descuento15[14] = {992, 788, 987, 90, 155, 596, 27, 587, 98, 273, 344, 69, 89, 234};
char respuesta;
int listacompra[100][1];
int precio;
int colector = 0;
int comprobante = 0;
int total;
int monto;
//Si la id del producto no esta dentro del rango valido, el bloque se repite
do{
do{
do{
printf("Escriba la ID del producto: ");
scanf("%d", &idprompt);
}
while(0==rangoValido(1,1000,idprompt));
//Una vez comprobada la validez del numero ingresado, se crea un numero aleatorio que se le
asigna para el precio, idprompt es la misma id
comprobante = 0;
srand(idprompt);
productoid[idprompt][1]=numeroRandom();
printf("ID del producto: %d\n", idprompt);
printf("Precio del producto: %d\n", productoid[idprompt][1]);
precio = productoid[idprompt][1];
//Comprobacion de descuentos
for(int i=0; i<=14; i++){
if(descuento25[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],25);
printf("Descuento del producto: 25\n");
}else{
if(descuento15[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],15);
printf("Descuento del producto: 15\n");
}
}
}
//Anadiendo el producto al carro de compras y comprobando la respuesta
do{
printf("Quieres anadir este producto a tu carrito de compras? (Y/N) ");
scanf(" %c", &respuesta);
}while(2 == sino(respuesta));
}while(respuesta == 'n' || respuesta == 'N');
if(respuesta == 'y' || respuesta == 'Y'){
listacompra[colector][0] = idprompt;
listacompra[colector][1] = precio;
colector = colector + 1;
}
do{
printf("Quieres seguir comprando? (Y/N) ");
scanf(" %c", &respuesta);
printf("\n");
if(0 == sino(respuesta)){
for(int i=0; i<colector; i++){
printf("\nID del producto %d: %d\n", i+1, listacompra[i][0]);
printf("Precio del producto %d: %d\n", i+1, listacompra[i][1]);
}
}
if(1==sino(respuesta)){
comprobante = 1;
}
}while(2==sino(respuesta));
}while(comprobante==1);
for(int i=0; i<colector; i++){
total = total + listacompra[i][1];
}
printf("\n\nTotal a pagar: %d\n", total);
printf("Ingrese monto recibido: ");
scanf("%d", &monto);
printf("\n");
if(monto<total){
printf("%d faltantes.", total-monto);
}
if(monto>=total){
printf("Vuelto: %d", monto-total);
}
return 0;
}
int numeroRandom(){
int random;
random = rand();
if(random>3000 && random<10000){
random = random / 5;
}
if(random<100){
random = random * 3;
}
if(random>10000){
random = random / 13;
}
return random;
}
int rangoValido(int Rangomin, int Rangomax, int i){
if(i>=Rangomin && i<=Rangomax){
return 1;
}else{return 0;}
}
int descuento(int num, int descuento){
num = num * (descuento / 100);
return num;
}
//Si la funcion sino() regresa 0, entonces la respuesta fue no. Si es 1, la respuesta es si. Y si
es 2, la respuesta es invalida.
int sino(char sino){
if(sino=='y' || sino=='Y'){
return 1;
}
if(sino=='n' || sino=='N'){
return 0;
}
else{return 2;}
}
I am writing a c program that calculates the root of a function and sometimes I put the wrong numbers ( like 3.333 instead of 33.333) and I don't want to run or exit the program if I can just restart/reload from the top.
It's also a way to run the program multiple times. kill 2 birds with one stone.
I am Portuguese, so sorry for the not-so-good English.
#include <stdio.h>
#include <math.h>
float main()
{
char let = 'a';
int b;
float x0, erro, gx, x1,dif, gxlinha, absgxlinha;
int it,val,i, exp, numero, e;
it=0;
int num = 0;
printf("Valor de x0 = ");
scanf("%f", &x0);
printf("Valor do erro = ");
scanf("%f", &erro);
printf("Qual o valor do expoente maior = ");
scanf("%d", &exp);
printf("\n");
val = (exp + 1);
printf("funcao do tipo: \n\n ");
e = exp - 1;
numero = exp;
for(b=0;b<=e;b++)
{
printf("%cx^%d + ",let,numero);
let++;
numero--;
}
printf("%cx^%d",let,numero);
printf("\n\n");
float a[val];
printf("Introduza os %d numeros da funcao, de acordo com os valores pedidos: \n",val); // ex.: ax^2 + bx^1 + cx^0 itroduzir pela ordem c, b, a
printf("\n");
for( i=0; i<val; i++ )
{
printf ("%c = ",let);
let--;
scanf("%f", &a[i] );
gx = gx + (a[i])*(pow((x0),num));
num++;
}
num = 1;
for (i=1; i<val; i++)
{
gxlinha = gxlinha + ((a[i]*num)*(pow((x0),num)));
num ++;
}
absgxlinha = (sqrt(pow(gxlinha,2)));
if ( absgxlinha < 1)
{
printf ("\ng(x0)' < 1 logo a funcao tem pelo menos uma raiz\n");
x1=gx;
dif = (sqrt(pow((x1-x0),2)));
printf("\n| Iter.| Val de x0| g(x0)=x1 | x1-x0 |\n| | | | |\n| %d | %f | %f | %f | ",it,x0,x1,dif);
while (sqrt(pow((x1-x0),2))>=erro)
{
x0 = x1;
gx = 0;
num = 0;
for( i=0; i<val; i++ )
{
gx = gx + (a[i])*(pow((x0),num));
num++;
}
x1=gx;
dif = (sqrt(pow((x1-x0),2)));
it++;
printf(">= %f\n| %d | %f | %f | %f | ",erro,it,x0,x1,dif);
}
printf("< %f \n\n",erro);
printf("A raiz com erro inferior a %f = %f",erro,x1);
printf("\n\n\n\n");
}
else
{
printf ("\ng(x0)' > 1 logo a funcao nao tem raizes\n");
}
}
where are some inputs in order
0.8 , 0.000005 , 3 , 0.333333 , 0 , 0 , -0.333333
As others have already said, you need a loop, maybe inside a dedicated function.
This is just an example:
while(1)
{
float x;
scanf(" %f", &x);
if (x < 0) // or any other condtion you want
break;
// your code
}
You need a loop. For example:
for (;;) {
if (// some condition) {
break;
} else {
//your code
}
}
I can't get out of this:
In the following code, if I choose option 1, I let the code begin asking the input described on 1/* InserimentoNaviP1 */; but when the program runs, without error in compiling, the function main() avoids it; the first printf is
("P1: inserisci la riga dove fare fuoco: ");
Can you please help me?
Below a part of the code (I cannot insert it all)
main() {
scanf("%d", &a);
switch (a) {
case 1:
printf("Che vinca il migliore!! \n");
break;
return 0; // Unreachable code...
}
Sleep(1000);
InizializzaGrigliaP1();
InizializzaGrigliaP2();
/* InserimentoNaviP1 */
for (r = 0; r < righe; r++) {
for (c = 0; c < colonne; c++) {
printf("Inserisci riga %d e colonna %d: ", r, c);
scanf("%d", &grigliaP1[r][c]);
}
if (grigliaP1[r][c] == 1) {
printf("nave inserita!\n");
contnum_naviP1++;
printf("restano da inserire %d navi!\n", P1_num_navi - contnum_naviP1);
}
}
for (t = 0;; t++) {
//SparaP1
{
printf("P1: inserisci la riga dove fare fuoco: ");
system("pause");
}
} // added
} // added