0

I'm a beginner to C, and I'm having some trouble formatting a simple printf function that takes two integers, a & b and prints out a^2 + b^2 = c, where I assign c to be a*a + b*b..

That being said, I'm not sure how the parameters of C's printf statement work, this is what I wrote:

printf("%i,a ^2 + (%i,b) ^2 = %i,c", a, b, c); 

And this is what it's printing

3,a ^2 + (4,b) ^2 = 25,c10,a ^2 + (10,b) ^2 = 200,c 

Which isn't too far off, I just don't know how to get rid of the ugly variables & parenthesis I have going on like (4,b)

This is what it is supposed to look like. I know I'm missing a "\n" in there somewhere also.

3^2 + 4^2 = 25 10^2 + 10^2 = 200 
0

3 Answers 3

8
printf("%i^2 + %i^2 = %i\n", a, b, c); 

You don't need to put a, b, c in the string, because the string is used as a template where %i will be substituted with the given parameters. You just need to add them after the string, in the correct order.

Everything that does not start with % will be printed as it is, as in your case with letters and parenthesis.

Sign up to request clarification or add additional context in comments.

2 Comments

So essentially you just put the parameters a b & c at the end so they don't LITERALLY print a b and c?
Exactly, just put them in the correct order, in the same number as %i you have.
4

When you put a in the quotes in the first parameter, you get a literal a, not the value of a.

You want to do something like this:

printf("%i^2 + %i^2 = %i", a, b, c); 

The ,a notation you have doesn't work. You use %i as a placeholder for an integer, then pass the integer as a separate parameter. So, in the version I wrote above, you have three placeholders, then pass in three variables as additional parameters.

Comments

3

Also you can use printf("%d^2 + %d^2 = %d", a, b, c) for integers too. If you need to parse doubles you can use printf("%f^2 + %f^2 = %f", a, b, c). I recommend that you read the book "The C Programming Language II Edition", a really good book. Chapter Seven is about Input and Output.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.