Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
November 17th, 2012, 10:44 PM
 lalaman74
Registered User

Join Date: Nov 2012
Posts: 4
Time spent in forums: 1 h 47 m 44 sec
Reputation Power: 0
Printf Problem

The program seems to print out the s and c values for every integer up until n, including n, but I only want to print out the values of s and c for n. Any help with this problem?
Code:
```#include <stdio.h>
#include <math.h>

int main()
{
double n,s,c;
while(scanf("%d", &n)&&n)
{
s=(2*pow(n,3)+3*pow(n,2)+n)/6;
c=pow(n*n+n,2)/4;
printf("%d %d\n", s,c)
}
return 0;
}```

#2
November 17th, 2012, 11:09 PM
 dwise1_aol
Contributing User

Join Date: Jan 2003
Location: USA
Posts: 6,862
Time spent in forums: 3 Months 1 Day 6 h 58 m 54 sec
Reputation Power: 2199
%d is to output a decimal integer. s and c are not integers, but rather double (double precision floating-point). Their internal formats are completely different. You are telling the compiler to misrepresent floating-point values as if they were integer, the results of which is incomprehensible garbage.

%f and %g are used for floating point. You should also consider using them in the scanf, since you are now telling scanf to store an integer value in the memory location of a double, thus immediately turning the input value into instant garbage as the program will thereafter misinterpret that integer as a floating-point value, a really messed up one. Garbage in, raised to the garbage power, rehashed as new garbage on the way out ... you've got a real mess on your hands there.

So input and output those floating-point values as floating-point. After you've gotten that corrected, then come back with more questions.

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Printf Problem