Why appears the wrong number - c

the code doesn't work and i don't know why but i'm a begginer in this language so the fault could be mine
#include <stdio.h>
int horascomeco(){
int horasco; int minutosco; int totalcomeco;
printf("-----A que horas e minutos começou o recolher?\nHoras:");
scanf("%d", &horasco);
printf("Minutos:");
scanf("%d", &minutosco);
printf("R:O recolher começou ás %d horas e %d minuto\n\n\n", horasco, minutosco);
totalcomeco = horasco*60 + minutosco;
printf("%d\n", totalcomeco);
return totalcomeco;
}
int horasapanhado(){
int horasapa; int minutosapa;int totalapanhado;
printf("-----A que horas e minutos foi apanhado?\nHoras:");
scanf("%d", &horasapa);
printf("Minutos:");
scanf("%d", &minutosapa);
printf("R:Voce foi apanhado ás %d horas e %d minutos\n\n\n", horasapa, minutosapa);
totalapanhado = horasapa*60 + minutosapa;
printf("%d\n", totalapanhado);
return totalapanhado;
}
int tempodemulta(){
int minutosforadalei;
int horascomeco;
printf("%d\n", horascomeco);
int horasapanhado;
printf("%d\n", horasapanhado);
minutosforadalei = horasapanhado - horascomeco;
printf("A sua multa vai ser respetiva a %d minutos fora do recolher obrigatorio", minutosforadalei);
}
int main(){
horascomeco();
horasapanhado();
tempodemulta();
return 0;
}
why appears 14705... ? minutosforadalei should be = 1 in that print

int tempodemulta(){
int minutosforadalei;
int horascomeco;
printf("%d\n", horascomeco); // no value assigned to horascomeco!
int horasapanhado;
printf("%d\n", horasapanhado); // no value assigned to horaspanhado!
minutosforadalei = horasapanhado - horascomeco;
printf("A sua multa vai ser respetiva a %d minutos fora do recolherobrigatorio", minutosforadalei);
}
You are printing and calculating with variables that you have not assigned any value to yet. You have to assign a value to a variable before you try to use that value.

Related

User entry array being filled with garbage

im trying to make this function work but the array keeps getting filled with trash. The cicle is running properly, I just cant seem to find the error.
int CargaArregloEnteros(int a[], int dim, int v);
void MostrarArreglo(int n[], int v);
int main()
{ int notas[100], validos=0;
validos = CargaArregloEnteros(notas, 100, validos);
printf("\nLos validos son %d\n", validos);
MostrarArreglo(notas, validos);
return 0;
}
int CargaArregloEnteros(int a[], int dim, int v)
{
char opcion=0;
while(v<dim && opcion !=27)
{
printf("\n Ingrese una nota a cargar ");
fflush(stdin);
scanf("&d", &a[v]);
printf("\n Presione ESCAPE para salir\n");
fflush(stdin);
opcion=getch();
system("cls");
v++;
}
return v;
}
void MostrarArreglo(int n[], int v)
{
for(int i=0;i<v;i++)
{
printf("%d | ", n[i]);
}
}
You need to change
scanf("&d", &a[v]);
to
scanf("%d", &a[v]);
so that it constitutes a valid conversion specifier syntax.
Also, a good lesson on why it's best to check the return value of scanf() and other library functions.

Solved: Routine with Do While and For make a unknow error GCC Core dump (Segment fault)

After compiling this program with GCC (Linux or Windows or online test compiler), it fails in different ways each time it runs. I don't understand where I made the mistake.
On Ubuntu Linux, the program crashes without printing an answer.
On Windows 10 (MSYS), it loops indefinitely without printing any message.
On an online compiler I tried, it fails with a segmentation fault (and core dump and exit code 139).
Here is the code:
#include <stdio.h>
int main() {
float riga[1][3];
int ciclo = 2;
int calcolo;
float totale;
int codice = 0;
int quanti = 1;
int prezzo = 2;
printf("\n Inserendo una quantita pari a 0 si conclude con il totale");
do {
codice++;
printf("\n Numero: %d Inserire la quantita:", codice);
scanf("%f", &riga[codice][quanti]);
if ( riga[codice][quanti] < 1 ){
printf("\n Calcolo del totale.");
ciclo = 1;
} else {
printf("\n Numero: %d Inserire il prezzo:", codice);
scanf("%f", &riga[codice][prezzo]);
}
//printf("\n Quantita: %f Prezzo: %f", riga[codice -1][quanti], riga[codice -1 ][prezzo]);
//printf("\n Ciclo = %d", ciclo);
} while( ciclo != 1 );
printf("\n Totale in calcolo");
for ( calcolo = 1; calcolo < (codice + 1); calcolo++){
//printf("\n Prezzo = %f",riga[calcolo][prezzo] );
totale = totale + (riga[calcolo][prezzo] * riga[calcolo][quanti]);
}
printf("\n Totale: %f", totale);
return 0;
}
What is wrong with it?
1.don't use uninitialized variables and you should initialize totale.
2.don't pass boundaries of your array or it will cause undefined behavior.
here in this declaration float riga[1][3]; ,first dimension has only one element.Your increment here codice++; is invalid you don't have riga[1][num] you only have riga[0][num].So remove this line codice++; and also check in your while condition that you won't scan more than 3 elements for second dimension of array.
here
for ( calcolo = 1; calcolo < (codice + 1); calcolo++){
totale = totale + (riga[calcolo][prezzo] * riga[calcolo][quanti]);
}
again you are passing boundaries of array. calcolo could only be zero.
as #John Bollinger said underlying point about arrays: they are indexed from 0, not from 1.

storage of a result in a vector

I have tried to store a result in a vector and then to print all those stored values, I think I'm very far, but that's what I was able to develop until now, I'd like some help on what's wrong and how it could you do it, thank you and good night
#include <stdio.h>
int main(void) {
int i;
int x;
int vetor[]={};
int a, b;
int resultado;
printf("Quantos resultados esse vetor vai receber tem ? ");
scanf("%d", &x);
printf("\n");
for(i=1; i<=x; i++){
printf("Digite valores para serem somados e armazenados no vetor:\n");
scanf("%d%d", &a, &b);
resultado = a+b;
resultado = *vetor;
printf("vetor contém: %d\n", *vetor);
}
printf("\n");
printf("você conseguiu !!!");
return 0;
}
`````````````````````````````````````````````````````````````````´´´´
#include <stddef.h>
#include <stdio.h>
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
#define ARRAY_SSIZE(arr) ((ptrdiff_t)ARRAY_SIZE(arr))
int main(void)
{
ptrdiff_t x;
int a, b;
int resultado;
printf("Quantos resultados esse vetor vai receber tem ? ");
scanf("%ti", &x);
int vector[x] = {0};
printf("\n");
for (ptrdiff_t i = 0; i < ARRAY_SSIZE(vector); i++) {
printf("Digite valores para serem somados e armazenados no vetor:\n");
scanf("%d%d", &a, &b);
resultado = a + b;
vector[i] = resultado;
printf("vetor contém: %d\n", vetor[i]);
}
printf("\n");
printf("você conseguiu !!!\n");
return 0;
}
You should give the array (not vector) a size (x in this case) to create it.
Assignments (a = b;) work this way: the program calculates whatever is on the right hand side, and copies that value into the variable that is on the left hand side of the =.
When you use (access, write, ...) an array, you have to specify the index (position) of the array you want to use.
It is better to use sizeof to calculate the size of an array for loop limits so that if you change the declaration of the array, the code still works (see ARRAY_SIZE, and ARRAY_SSIZE which is a signed version, so that comparison is done between integers of the same sign, to avoid unexpected bugs).
Always end your last printf with a \n, so that it doesn't get mixed with other text in the terminal.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [C]

I am trying to compile the following code on Ubuntu (64-bit), with Dev-C++ 5.9.2
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Afficher les nombres parfaits inférieurs ou égaux à un entier donné
void parfaitInf(int n)
{
int i, j, somme;
for(i=2;i<=n;i++)
{
somme=1;
for(j=2;j<=i/2;j++)
{
if(i%j==0) somme+=j;
}
if(somme==i) printf("%d\n",i);
}
}
// Tester si un entier est un nombre d'Armstong
void armstrong(int n)
{
int somme=0,m=n;
do
{
somme+=pow(m%10,3);
m/=10;
}
while(m!=0);
if(somme==n) printf("%d est Armstrong.\n",n);
else printf("%d n\'est pas Armstrong !\n",n);
}
// Calculer la racine carrée d'un nombre entier
void racineCarree(int n)
{
printf("La racine carr%ce de %d est %f",130,n,sqrt(n));
}
void menuPrincipale(int *choix)
{
do
{
printf("\t\tMenu\n");
printf("[1] Afficher les nombres parfaits inf%rieurs ou %cgaux %c un entier donn%ce\n",130,130,133,130);
printf("[2] Tester si un entier est un nombre d\'Armstrong\n");
printf("[3] Calculer la racine carr%ce d\'un nombre entier\n\n",130);
printf("Votre choix ? ");
scanf("%d",&choix);
}
while(&choix<1 || &choix>3);
}
int main()
{
int n,choix;
menuPrincipale(choix); //compilation error here
printf("%d",&choix);
// Not Continued
return 0;
}
On line 51, my compiler gives me the error "ISO C++ forbids comparison between pointer and integer [-fpermissive]".
On line 57, my compiler gives me the error "[Error] invalid conversion from 'int' to 'int*' [-fpermissive]"
Why doesn't this work? I want to understand the current problem.
basic of pointers
int i = 1;
int *p = &i; // p is a memory address of where i is stored. & is address of variable.
int j = *p; // j is the value pointed to by p. * resolves the reference and returns the value to which the pointer addresses.
int **dp = &p; // dp is the address of the pointer that itself is an address to a value. dp->p->i
cout << i; // 1
cout << p; // 0x.... some random memory address
cout << j; // 1
cout << dp; // 0x... some random memory address that is where the p variable is stored
so as your your issue, as others said in menuPrincipale() your incorrectly using pointers.

caesar cipher in C, using arrays and chars, I get an error in the numbers

Here is the code, basically I gotta do the ceasar cipher in C using arrays and chars only, here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
main ()
{
char alfabeto[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int a=0;
int b=0;
int m=0;
int c=0;
//char letra;
int cont=0;
char k[]={};
printf("Introduzca un primer numero 'a':\n");
scanf(" %i", &a);
printf("Introduzca un segundo numero 'b':\n");
scanf(" %i", &b);
printf("Introduzca una palabra clave entre 4 y 10 letras (cuando termine presione '.'):\n");
//Falta una validacion para la palabra.
for (int j=0;j<10;j++)
{
scanf(" %c",&k[j]);
cont=j; //cuenta la cantidad de elementos
if (k[j]=='.')
{
j=10;
}
}
for(int j=0;j<cont;j++) //Error in this bit I think.
{
for (int i=0;i<26;i++)
{
if (alfabeto[i]==k[j])
{
m=i;
i=26;
}
}
c = ( (a * m) + b );
printf("%c es: %i \t",k[j],c);
}
}
It uses a formula where c=(a*m+b).
m being the position of the original letter for example: A=0 then m=0.
a being a number you choose as well as b.
In my case I chose a=1 and b=3 and the word CESAR as the key word.
According to the formula the output number of each letter should be c.
The output should be:
C es: 5 E es: 7 S es: 21 A es: 3 R es: 20
Yet it is this:
WrongOutput
UPDATE:
I had to correct this:
char k[]={};
Into this:
char k[10]={'\0'};
Now I get the right output:
Right Output

Resources