Why is the result of my operation being printed printing 00 and not the actual result?

Asked

Viewed 59 times

2

I’m practicing syntax in C language,a code about voting, wrote an excerpt of the code and went to compile to test, casting, and it didn’t work, I typed with int, double, float and nothing,%d,%f %i and nothing...

#include <stdio.h>
#include <stdlib.h>
#include<locale.h>

int main(int argc, char*argv[])
{
    setlocale(LC_ALL,"portuguese");

    double totalv=0, vnulos=0,vbrancos=0,vvalidos=0;
    double v,n,b;

    printf("digite a quantidade de votos brancos\n");
    scanf("%d",&vbrancos);
    printf("digite a quantidade de votos nulos\n");
    scanf("%d",&vnulos);
    printf("digite a quantidade de votos válidos\n\n");
    scanf("%d",&vvalidos);
    totalv=vbrancos+vnulos+vvalidos;

    if(vnulos>0){
        n=(vnulos/totalv)*100;
        printf(" foram um total de %.2d de votos nulos totalizando um percentual de %d %%",vnulos,n);

    }else{
        printf("valor incompatível\n tente novamente\n");
    }

    return 0;
}

1 answer

3


I believe your mistake was changing the types of variables and not changing the conversion specifiers of printf and of scanf

See your code working properly:

#include <stdio.h>
#include <stdlib.h>
#include<locale.h>

int main(int argc, char*argv[])
{
    setlocale(LC_ALL,"portuguese");

    float totalv=0, vnulos=0,vbrancos=0,vvalidos=0;
    float v,n,b;

    printf("digite a quantidade de votos brancos\n");
    scanf("%f",&vbrancos);

    printf("digite a quantidade de votos nulos\n");
    scanf("%f",&vnulos);

    printf("digite a quantidade de votos válidos\n");
    scanf("%f",&vvalidos);

    totalv=vbrancos+vnulos+vvalidos;

    if(vnulos>0){
        n=(vnulos/totalv)*100;
        printf("votos total %f \n", totalv);
        printf(" foram um total de %.2f de votos nulos totalizando um percentual de %f %%",vnulos,n);

    }else{
        printf("valor incompatível\n tente novamente\n");
    }

    return 0;
}

Behold working in the ideone.

Fixes in your code:

I changed your variables to type float, due to the use of the percentage. Note in printf and in the scanf that the conversion specifiers have been changed to %f.

However, don’t just copy the code.

I recommend reading:

How to read from stdin in C?

Difference between %i and %d

Syntax of format specification

  • I had changed the variables, but I believe you sin in forgetting some specifier, I did now as you suggested and it really worked, I finish the code and it was like this:

  • @crisman acredtio that was just that. needing some help just ask! Or reopen other questions, be sure to elaborate a Minimum, Complete and Verifiable Example to demonstrate the problem you’re going through

Browser other questions tagged

You are not signed in. Login or sign up in order to post.