n00b Problems with Printf and Rounding

I'm a n00b C++ programmer so please bear with me.

I have squared a number in a float variable and printed it out, but it only prints it as a rounded-up integer and not the fraction. Any idea why ?

Also tried using printf(total number); but Xcode says "no matching function for call to 'printf'. Why doesn't it just print the value of totalnumber ?

1
2
3
4
5
  float firstnumber = 256.78;
    float totalnumber = 0;
    totalnumber = firstnumber * firstnumber;
    printf("total is ");
    std::cout << totalnumber;


Thanks
try just using printf or cout
but not both!

if you want to use cout
then look at this
http://www.cplusplus.com/reference/iomanip/setprecision/

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
    float firstnumber = 256.78;
    float totalnumber = 0;
    totalnumber = firstnumber * firstnumber;
    printf("total is %.2f", totalnumber);
    return 0;
}


output
total is 65935.97
Last edited on
Ah so you have to tell printf how to format a variable by using the % symbol ?

S
Your mixing C and C++ in your code, printf is C, cout is C++ - you shouldn't be using both.

With regards to printf, check out this link which gives all the format specifiers for printf.

http://www.cplusplus.com/reference/cstdio/printf/



256.78 * 256.78 gives exactly 65935.9684.
When you use cout <<, the default precision is 6 significant digits which would be 65936

Thus, the displayed result has not omitted the fractional part. Rather it has correctly displayed the result to 6 significant digits.
Make sure your including the right things.
#include <iostream> or really old version #include <iostream.h> to use cout, cin and endl.
#include <stdio.h> to use printf.

How to use printf:
printf("text %variable",number);
If you want to add more variables, keep adding at the back:
printf("text %variable1 %variable2",number1, number2);
Topic archived. No new replies allowed.