Variable percentage in c

Asked

Viewed 1,857 times

0

I have a problem with a simple code, I want to know how to calculate the percentage of a value.

EX: 1500 + 15% (in this case I know it is value = value*0.15)

However, the percentage value must be a variable informed by the user. So far I have the following code but I don’t think it will help.

#include <stdio.h>

//Escreva um programa que leia: o valor de uma aplicação, o
//percentual de rendimento mensal obtido por esta aplicação e o
//período do investimento; e retorne o valor da aplicação ao final do
//período de investimento.

int main (){

    float aplicacao = 0;
    float rendimento = 0;
    float ff = 0;
    int periodo = 0;
    int cont = 0;

    while (cont < periodo){
        ff = aplicacao + rendimento
        cont ++
    }

}
  • Wouldn’t that be 15/100 ?

  • @Sveen did you mean 15.0/100, Isn’t that right? In C, if you have no reason to split floating points, this division will not be made. This is why it is important to ensure that the numerator or denominator is a floating point number

  • How will this percentage be informed? It will be typed 15 to represent 15%? Or will be typed 15.0? Or even 0.15? And accepts less than 1%? For example, it makes sense for the user to enter some value that represents 15.3%?

2 answers

-2

First you need the float value, that is, divide the percentage value by 100. Be careful with conversions ( int result = desc / 100 would result in 0, as decimals would be truncated when converting from float to int). With that, just do the multiplication.

-3


One solution to this would be to receive an integer number and then divide it by 100 as well as in the code below:

  int Num;
  float percen;
  cout << "Lendo a porcentagem...: ";
  cin >> Num;
  percen = Num/100;

You can learn more about the methods Cin and Cout on the link: https://www.inf.pucrs.br/~pinho/PRGSWB/Streams/streams.html

  • Your answer has several errors. The first is that you answered a C question with C++ stuff without giving due warning. Yes, this is an important thing to do. And C and C++ are not the same language. The second thing is that you are performing entire division of any sort, not catching the fractional part arising from division. So if the person enters with 99, their variable percen carry with it the value 0.0, nay 0.99.

Browser other questions tagged

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