Reputation: 45
For this assignment I want my program to output the requested output. My issue lies in the formatting.
Link to the problem in question:
The output of the program:
For whatever reason my x value is not increasing by a factor of ten and as far as the spacing is concerned I am not sure what I am doing wrong.
#include <stdio.h>
//declare global variables
int x = 1;
double num = .1234;
//prototype functions
partA(double num);
int main() {
double a;
a = partA(num);
printf("%lf\n",a);
}
/*First Function, x and num increase by a factor
of ten. */
partA(double num) {
for(x; x <= 10000; x *= 10) {
for (num; num <= 1234; num *= 10) {
printf("%d%4lf\n",x, num);
}
printf("\n");
}
}
Upvotes: 1
Views: 232
Reputation: 153498
After accepted answer. This one uses fields widths and not spaces as required by the post.
#include <stdio.h>
void partAB(const char *format, double num) {
double d = 1.0;
for (int i = 0; i<5; i++) {
printf(format, d, num);
d *= 10;
num *= 10;
}
printf("\n");
}
void partA(double num) {
partAB("%5.0lf %.4lf\n", num);
}
void partB(double num) {
partAB("%5.0lf %9.3le\n", num);
}
int main() {
double x = 0.1234;
partA(x);
partB(x);
return 0;
}
Upvotes: 0
Reputation: 3653
Without if, switch and spaces and tabs in printf format it will be like this
partA(double num) {
const int const max = 10000;
const int const precision = 4;
int width = 1 + log((float)max) / log(10.0f);
for(; x <= max; x *= 10, num *= 10) {
printf("%*d%c%.*f\n", width, x, 040, precision, num);
}
}
Upvotes: 1
Reputation: 2161
It is not increasing because you have a For inside another For, you have to increment X inside the For of "num"
Something like:
int x = 1;
for (num; num <= 1234; num *= 10)
{
printf("%5d%3s%4lf\n",x, " ", num);
x*=10;
}
Cheers
Edit: before I forgot the spaces, it should be fine now
Upvotes: 1
Reputation: 1670
this code:
#include <stdio.h>
int ee(int e){
int i, ret;
ret=1;
for(i=0;i<e;i++)
ret *= 10;
return ret;
}
int main(void) {
int i;
printf("a)\n");
for(i=0;i<5;i++)
printf("%5d %.4f\n",ee(i), 0.1234 * ee(i));
printf("\nb)\n");
for(i=0;i<5;i++)
printf("%5d %.3e\n",ee(i), 0.1234 * ee(i));
}
gives:
a)
1 0.1234
10 1.2340
100 12.3400
1000 123.4000
10000 1234.0000
b)
1 1.234e-01
10 1.234e+00
100 1.234e+01
1000 1.234e+02
10000 1.234e+03
Upvotes: 1
Reputation: 4818
The spacing is because only outer loop is executing which contains printf
Upvotes: 1
Reputation: 34823
See the documentation for printf format strings.
To change the number of digits after the decimal point, specify the precision.
To get a space between the numbers, use a literal space in the format string, as in
printf("%d %4lf\n",x, num);
Upvotes: 0