I'm a beginner in programming and can't get the while loop to function properly. Please take a look and see what's wrong with the while loop.. or anything else that might be affecting it.
#include <stdio.h>
#include <math.h>
int main (void) {
int iP, fP, t, incr, tmax;
float r;
t = 0;
printf("Enter the initial bacteria population: ");
scanf("%d", &iP);
printf("Enter the bacterial growth rate: ");
scanf("%f", &r);
printf("Enter the time that the bacteria is allowed to reproduce (in minutes): ");
scanf("%d", &tmax);
printf("Enter the increment of time (in minutes) you would like to measure: ");
scanf("&d", &incr);
if (( r < 0.0)|| (r > 1.0)) {
printf("You must enter a number greater than 0 and less than 1!");
return 1;
}
while (t <= tmax) {
fP=iP*exp(r*t);
printf("In %d minutes the bacteria population is %d\n", t, fP);
t = t + incr;
}
return 0;
I'm using C programming but I thought I could ask here as well. I've only been able to make the while loop stop instantly at 0mins with user inputed population and another method I used has the while loop going on indefinitely.
What function are you trying to represent on line 27 (26 in the code below)? Also, what are your inputs? Your expected output? Your actual output? Here's your code with more expressive variable names and better whitespacing (makes it easier to read IMO):
#include <stdio.h>
#include <math.h>
int main () {
int initialPop, currentPop, currentTime, timeIncrement, finalTime;
float growthRate;
currentTime = 0;
printf("Enter the initial bacteria population: ");
scanf("%d", &initialPop);
printf("Enter the bacterial growth rate: ");
scanf("%f", &growthRate);
printf("Enter the time that the bacteria is allowed to reproduce (in minutes): ");
scanf("%d", &finalTime);
printf("Enter the increment of time (in minutes) you would like to measure: ");
scanf("%d", &timeIncrement);
if (( growthRate < 0.0)|| (growthRate > 1.0)) {
printf("You must enter a number greater than 0 and less than 1!");
return 1;
}
while (currentTime <= finalTime) {
currentPop = initialPop * exp(growthRate*currentTime);
printf("In %d minutes the bacteria population is %d\n", currentTime, currentPop);
currentTime = currentTime + timeIncrement;
}
return 0;
}