Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

function - Calculating percentages in C

I am trying to find out how percentages are calculated within C, and specifically I am trying to find out how much taxes you get from user input, if the tax would be 21%.

But after trying the code in the terminal with input : 130, which means I want 21% of 130$, it gives me a negative value of -858993459

How do Ifix this or where did I go wrong?

All of my google searches come up empty too, but probably because I am not using the correct phrasing so all info is welcome.

#include <stdio.h>

double get_tax_amount(double price_including_taxes)
{
  return price_including_taxes *0.21;
}

int main()
{
  printf("What was your price? ");
  double price;
  scanf("%d", &price);
  printf("The tax price is: %d", get_tax_amount (price));      
}
question from:https://stackoverflow.com/questions/65884070/calculating-percentages-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You’re using the wrong conversion specifier in both scanf and printf. To read a double value with scanf you need to use %lf and to print a double value with printf you need to use %f.

Because of how those functions work, they don’t know the number, type, or order of arguments you’ve actually passed to them - they just see a sludge of bytes on the stack or a sea of argument registers. The only way for them to know what arguments they should expect is through what you specify in the format string.

%d is used to read and print int types, %c for individual characters, %s for strings, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...