This is a simple program to calculate the length of lines. All the calculation aspects of the program are done and working.
But I am having trouble on one very simple aspect, the variable "percent_detoured" is declared on line 10 and used on line 83, and printed on line 84. Problem is when executed, everything else runs fine but percent_detoured consistently returns 0.000. When debugged, percent_detoured does not even show as a variable in "Locals".
I am using Pelles C IDE if that helps.
Thanks for the help!
{
float line_value;
int x_1, y_1, x_2, y_2;
float y_intercept;
float distance, greatest_distance, total;
float percent_detoured; // <-- DECLARED HERE (SCROLL ALL THE WAY DOWN TO SEE WHERE IT IS USED)
int count, detour_count;
x_1=1; y_1=1; x_2=1; y_2=1;
greatest_distance = 0; total = 0; count = 0; detour_count = 0;
/* Ask for user input in setting the coordinates of the line */
printf("Enter in the length of the line\n");
scanf("%f", &line_value);
/* If user enters in y coordinates for the line such that the line length is greater
than 10 units, then enter loop and continue looping until the length is smaller or
equal to 10 */
while ( line_value > 10 || line_value < 0)
{
printf("Try Again. Value should be smaller or equal to 10 units\n");
scanf("%f", &line_value);
}
line_value = line_value / 2; //Define the top of the line
printf("Enter x and y coordinates for point 1 and 2\n");
scanf("%d %d %d %d", &x_1, &y_1, &x_2, &y_2);
if ( x_1 == 0 && x_2 == 0 && y_1 == 0 && y_2 == 0 ) //If user enters in 0 0 0 0 right away, then immediately end the program
{
printf("No path lengths have been calculated\n");
}
else
{
/* While the user does not enter in the values 0 0 0 0 for all coordinates, continue while loop */
while ( (x_1 != 0) || (y_1 != 0) || (x_2 != 0) || (y_2 != 0) )
{
y_intercept = y_1 - ( (y_2 - y_1) / (x_2 - x_1) * x_1 ); //Rearrange (y=mx+b) to get (b=y-mx) where b is the y intercept
if ( y_intercept <= line_value && y_intercept >= 0 ) //If the y-intercept of the line from point a to b is between
{ //the top of L and 0, then calculate distance between a and top of L
distance = sqrt( pow(x_1, 2) + pow((y_1 - line_value), 2) )
+ sqrt( pow(x_2, 2) + pow((line_value - y_2), 2) );
detour_count++; //Updating the detour counter
}
else if ( y_intercept >= ( line_value * -1) && y_intercept < 0 ) //If the y-intercept of the line from point a to b is between
{ //the bottom of L and 0, then calculate distance between a and bottom of L
distance = sqrt( pow(x_1, 2) + pow( (y_1 + line_value), 2) )
+ sqrt( pow(x_2, 2) + pow(( y_2 - (line_value * -1) ), 2) );
detour_count++; //Updating the detour counter
}
else
{
distance = sqrt( pow((x_2 - x_1), 2) + pow((y_2 - y_1), 2)); //If shortest path between point a and b does not cross L,
} //then the distance is just the sum of squares of rise and run
if (distance > greatest_distance)
{
greatest_distance = distance; //If the current distance is greater than the previous, set it as the greatest distance
}
total = total + distance; //Total count of distance
count++; //Update general counter
printf("The shortest path is: %f\n", distance);
printf("Enter x and y coordinates for point 1 and 2\n");
scanf("%d %d %d %d", &x_1, &y_1, &x_2, &y_2);
}
}
printf("\nThe average path length: %f\n", (total/count));
printf("The length of the longest path: %f\n", greatest_distance);
percent_detoured = ((detour_count/count) * 100); // <-- USED IT HERE
printf("The percentage of paths involving a detour: %f\n", percent_detoured ); // <-- SHOULD BE PRINTED AS ITS VALUE HERE
return 0;
}
You should use
percent_detoured = ((float)detour_count/count) * 100.0);
Else, both detour_count and count are integers, and int divided by int will give an int. So assuming that detour_count < count, detour_count/count will be rounded to 0, multiplied by 100 (still 0) and finally rounded to float since it is being stored as a float (percent_detoured).
I never used the IDE you mentioned, so I have no clue why it might not be showing up in the debugger. :)
Related
I have problem I'm sitting with.
For example, suppose someone runs in straight lines and at constant speed between the positions on the left side of Table 1. The time they reach each position is shown next to the position. They stopped running at time 11. If the GPS records a position every 2 units of time, its readings would be the records on the right side of Table 1.
input:
The input consists of a single test case. The first line contains two integers n(2 <= n <= 100) and t(1 <= t <= 100), where n is the total number of positions on the running path, and t is the recording time interval of the GPS (in seconds).
The next n lines contain three integers per line. The i-th line has three integers Xi, yi (-10^6 <= xi, yi <=10^6), and ti (0 <= ti <= 10^6), giving the coordinates of the i-th position on the running path and the time (in seconds) that position is reached. The values of ti’s are strictly increasing. The first and last positions are the start and end of the run. Thus, t1 is always zero.
Given a sequence of positions and times for a running path, as well as the GPS recording time interval , calculate the percentage of the total run distance that is lost by the GPS. Your computations should assume that the runner goes at a constant speed in a straight line between consecutive positions.
My code can calculate the correct output out of the data from the picture but some of the test's will fail. The thing is that I dont now how the tests looks like. So I only know how the indata for the first test looks like.
int main(int arg, char* argv[]) {
int n, t;
int time, new_time, pos_x, pos_y, new_pos_x, new_pos_y;
double run_distance = 0, gps_distance = 0;
int gps_pos_x = 0, gps_pos_y = 0, gps_new_pos_x, gps_new_pos_y;
int gps_time = 0;
if(scanf("%d %d", &n, &t) != 2){
return 0;
}
if(scanf("%d %d %d", &pos_x, &pos_y, &time) != 3){
return 0;
}
for (int i = 0; i < n - 1; i++)
{
if(scanf("%d %d %d", &new_pos_x, &new_pos_y, &new_time) != 3){
return 0;
}
//Calculate run distance
run_distance += sqrt((new_pos_x - pos_x)*(new_pos_x - pos_x) + (new_pos_y - pos_y)*(new_pos_y - pos_y));
//Gps time
gps_time += t;
// Difference between new position X and old position X
int diff = new_pos_x - pos_x;
int pos;
// Difference between gps time and time of old position
int time_diff = gps_time - time;
// Calculate new gps position
pos = diff/(new_time - time) * time_diff + pos_x;
// Save new position
gps_new_pos_x = pos;
// Difference between new position Y and old position Y
diff = new_pos_y - pos_y;
// Calculate new gps position
pos = diff/(new_time - time) * time_diff + pos_y;
// Save new gps position
gps_new_pos_y = pos;
//printf("%d, %d\n", gps_new_pos_x, gps_new_pos_y);
//Calculate gps distance
gps_distance += sqrt((gps_new_pos_x - gps_pos_x)*(gps_new_pos_x - gps_pos_x) + (gps_new_pos_y - gps_pos_y)*(gps_new_pos_y - gps_pos_y));
pos_x = new_pos_x;
pos_y = new_pos_y;
time = new_time;
gps_pos_x = gps_new_pos_x;
gps_pos_y = gps_new_pos_y;
}
gps_distance += sqrt((pos_x - gps_pos_x)*(pos_x - gps_pos_x) + (pos_y - gps_pos_y)*(pos_y - gps_pos_y));
//float diffirence = run_distance - gps_distance;
float value = (run_distance - gps_distance)/run_distance * 100;
printf("%.15f\n", value);
return 0;
}
I'm facing some difficulties in the last few days while trying to finish the following task, I hope you guys can assist :
I'm given a single number N, and I'm allowed to perform any of the two operations on N in each move :
One - If we take 2 integers where N = x * y , then we can change the value of N to the maximum between x and y.
Two - Decrease the value of N by 1.
I want to find the minimum number of steps to reduce N to zero.
This is what I have so far, I'm not sure what is the best way to implement the function to find the divisor (someFindDevisorFunction), and if this 'f' function would actually produce the required output.
int f(int n)
{
int div,firstWay,secondWay;
if(n == 0)
return 0;
div = SomefindDivisorFunction(n);
firstWay = 1 + f(n-1);
if(div != 1)
{
secondWay = 1 + f(div);
if (firstWay < secondWay)
return firstWay;
return secondWay;
}
return firstWay;
}
For example, if I enter the number 150 , the output would be :
75 - 25 - 5 - 4 - 2 - 1 - 0
I see this a recursive or iterative problem.
OP's approach hints at recursive.
A recursive solution follows:
At each step, code counts the steps of the various alternatives:
steps(n) = min(
steps(factor1_of_n) + 1,
steps(factor2_of_n) + 1,
steps(factor3_of_n) + 1,
...
steps(n-1) + 1)
The coded solution below is inefficient, but it does explore all possibilities and gets to the answer.
int solve_helper(int n, bool print) {
int best_quot = 0;
int best_quot_score = INT_MAX;
int quot;
for (int p = 2; p <= (quot = n / p); p++) {
int rem = n % p;
if (rem == 0 && quot > 1) {
int score = solve_helper(quot, false) + 1;
if (score < best_quot_score) {
best_quot_score = score;
best_quot = quot;
}
}
}
int dec_score = n > 0 ? solve_helper(n - 1, false) + 1 : 0;
if (best_quot_score < dec_score) {
if (print) {
printf("/ %d ", best_quot);
solve_helper(best_quot, true);
}
return best_quot_score;
}
if (print && n > 0) {
printf("- %d ", n - 1);
solve_helper(n - 1, true);
}
return dec_score;
}
int main() {
int n = 75;
printf("%d ", n);
solve(n, true);
printf("\n");
}
Output
75 / 25 / 5 - 4 / 2 - 1 - 0
Iterative
TBD
If you start looking for a divisor with 2, and work your way up, then the last pair of divisors you find will include the largest divisor. Alternatively you can start searching with divisor = N/2 and work down, when the first divisor found will have be largest divisor of N.
int minmoves(int n){
if(n<=3){
return n;
}
int[] dp=new int[n+1];
Arrays.fill(dp,-1);
dp[0]=0;
dp[1]=1;
dp[2]=2;
dp[3]=3;
int sqr;
for(int i=4;i<=n;i++){
sqr=(int)Math.sqrt(i);
int best=Integer.MAX_VALUE;
while(sqr >1){
if(i%sqr==0){
int fact=i/sqr;
best=Math.min(best,1+dp[fact]);
}
sqr--;
}
best=Math.min(best,1+dp[i-1]);
dp[i]=best;
}
return dp[n];
}
I am getting an error when compiling this code. Z is the final count of coins needed to make change with aim being to use minimum number of coins. I defined int Z = 0 near the top. I've tried adding int z again and changing type to f in print statement but no luck.
Here's the error:
error: format specifies type 'int' but the argument has type '<dependent type>' [-Werror,-Wformat]
greedy.c:77:16: error: use of undeclared identifier 'z'
printf("%i\n", z);
Here is my code. I am a beginner so any suggestions or corrections would be welcome.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
//prompt user for amount of change owed
float f;
int num; //amount of change
do
{
printf("O hai! How much change is owed?:\n");
f = get_float();
}
while (f < 0); //verify input is positive
num = round(f * 100); //rounds float
//commence making change
do{
int c, e, i, j;
int z = 0; //z = coins
if (num % 25 == 0) // verifies that num is divisible by 25 so only 25c coins necessary
{
z = (num/25) + z; // updates final number of 25c coins
}
else if (num % 25 > 0)
{
i = num / 25;
j = num % 25;
}
else if ((num / 25 < 0) || (num >=10 && num < 25)) //this means that f is less than 25 cents so has to be divided by 10 cent coins
{
num = c;
c = j + c; //add remainder of num to the number to start with
}
if (c % 10 == 0) // c is less than 25c but divisible by 10c pieces
{
z = (c / 10) + z; //d is the final number of 10c coins
}
else if (c /10 < 1) //this means it's less than 10c
{
c = e; // Then c must be less than 10c
}
else if (e % 5 == 0) // divisible by 5c pieces
{
z = (e / 5) + z; // g is the number of 5 cent pieces
}
else if (e % 5 < 0)
{
z = (e / 1) + z; //h is the number of pennies
}
}
while (num > 0); //num is rounded float
printf("%i\n", z);
}
Firstly, I suggest you should format your code properly with indents.
Then, the cause of error is that z is declared inside the block associated to do loop and printf("%i\n", z); is out of its scope.
To get rid of this error, declare z at the place where visible from the printf() call -- for example, just before the do loop.
Note that declaring int Z = 0 won't work because identifiers' names are case-sensitive in C.
Like already said, you are declaring z inside the do-while loop, so it's visible only inside the loop.
You should declare it before the loop starts, so you can use it after the loop ends as well. Like this:
int z = 0; //z = coins
do{
***YOUR CODE***
} while();
I wrote a program for finding a root of a fifth degree polynomial, in a range that the user decides as an input.
for example:
Please enter the coefficients of the polynomial:
-64 0 0 0 0 2
Please enter the range:
4 -5.7
Invalid range! Please enter the range:
2 3.5
The polynomial has a root: x=2.
My problem is in when I enter for example the range **10.4 10.2" the program can't compare between two values and decide that its an invalid range. For integers it works.
How do I fix this?
#include <stdio.h>
#define ZERO 0.00001
int main()
{
double a_0,a_1,a_2,a_3,a_4,a_5,end_of_range,beginning_of_range;
int x,root;
printf("Please enter the coefficients of the polynomial:\n");
scanf("%lf%lf%lf%lf%lf%lf", &a_0, &a_1, &a_2, &a_3, &a_4, &a_5);
printf("Please enter the range:\n");
scanf("%lf%lf", &beginning_of_range, &end_of_range);
while (beginning_of_range >= end_of_range)
{
printf("Invalid range! Please enter the range:\n");
scanf("%lf%lf", &beginning_of_range, &end_of_range);
}
x = beginning_of_range;
while (x <= end_of_range)
{
if ((a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x >= -ZERO)
&& (a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x <= ZERO))
{
root = x;
printf("The polynomial has the root x=%d.", root);
break;
}
x++;
if( x > end_of_range)
{
printf("Could not find a root.");
break;
}
}
return 0;
}
Note: I want the roots to be only Integers! that's why I declared x as an int.
And something strange is happening, when I enter the range [10.4, 10.3] it just wait for about 1 minute and then prints "Could not find a root", although it must print invalid range.
Things to change:
Change the type of x. Instead of
int x;
use
double x;
Declare root as a variable.
double root;
Fix the format used to print root. Instead of
printf("The polynomial has the root x=%d.", root);
use
printf("The polynomial has the root x=%lf.\n", root);
Make x a double, but let it only take on integer values.
// x = beginning_of_range;
x = ceil(beginning_of_range);
// while (x <= end_of_range)
while (x <= floor(end_of_range))
// x++
x += 1.0;
This approach will have trouble when |x| is large (about 1/DBL_EPSILON) as x += 1.0; may not result in a incremented x.
BTW:
double y = ((((a_5*x + a_4)*x + a_3)*x + a_2)*x + a_1)*x + a_0;
// is numerically more stable (and likely faster) than
y = (a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x;
Minor: Suggest removing = in range test. A range of [1 1] looks legitimate to me.
// while (beginning_of_range >= end_of_range)
while (beginning_of_range > end_of_range)
To test two 32-bit integers, m whose factorial is m! can be divisible by n. If it can, the function divides() returns 1, otherwise 0.
As the codes below, the problem is when m = 2010000, error happened. Could you please explain why?
#include <stdio.h>
long factorial(long n){
if((n == 0) || (n == 1)) return 1;
else{
return (n * factorial(n-1));
}
}
int divides (long n,long m)
{
long facN;
printf("n=%ld ",n);
facN = factorial(n);
if(m != 0){
if(facN == 1) return 0;
else{
if(facN % m == 0) return 1;
else if((facN % m) != 0)return 0;
}
}
else if(m == 0) return 0;
}
int main()
{
printf("%d", divides(2000000,1));
}
You need to compute the factorial with the modulus already taken into account. Using the following identity:
(a * b) % n = ((a % n) * (b % n)) % n
we can compute the factorial as:
m! % n = (((((1 % n) * 2) % n) * 3) % n) ...) % n
A 32-bit integer can only store factorials from 0 to 12.
1*2*3*4*5*6*7*8*9*10*11*12
479001600
1*2*3*4*5*6*7*8*9*10*11*12*13
6227020800
Given that 69! is of the order of 10^98 you are probably looking at value overflows but you might also be looking at running out of memory/stack as you will be nesting 2 million deep in your recursion.
Also your check if((facN % m) != 0) is redundant as it is called in the else to if(facN % m == 0)
If your cause is all about finding out whether if m! for an m is divisible by an n, do not calculate the factorial at all.
Rather split n to its factors, check if there are enough many of those inside the numbers ranging from 1 to m, inclusive.
For example; for m = 7 and n = 28, the process should be like the following:
n % 2 == 0 ? yes
n /= 2
2 * 1 <= m ? yes
n % 2 == 0 still? yes
n /= 2
2 * 2 <= m ? yes
n % 2 == 0 still? no
n % 3 == 0 ? no
...
n % 7 == 0 ? yes
n /= 7
7 <= m ? yes
n reached 1, return 1
Something like this. If you cannot manage to write this, then you probably shouldn't be dealing with that question yet. Still, if you want, leave a comment, I can edit my answer to include a working code.
I am adding a working example, using the logic above to display whether n is a divisor of m!, just to assure you that this thing does indeed work:
#include <stdio.h>
// this function basically compares the powers of the
// prime divisors of factee and divisor
// ... returns 1 if the powers in divisor are
// ... less than or equal to the powers in factee
// ... returns 0 otherwise
int divides( long factee, long divisor ){
int amount;
for ( int i = 2; i <= factee; i++ ){
if ( divisor % i )
continue;
amount = 0;
int copy = factee;
while ( copy ){
copy /= i;
amount += copy;
}
while ( divisor % i == 0 ){
if ( !amount )
return 0;
amount--;
divisor /= i;
}
if ( divisor == 1 )
return 1;
}
return 0;
}
int main( )
{
printf( "%d", divides( 20, 10000 ) );
getchar( );
return 0;
}
amount variable calculates the amount of i there are inside the m!. In the while loop in which it gets calculated, with the first cycle, the amount of is are added, then with the second cycle, the amount of i * is are added, and so on, until there aren't any.
For example, with m = 5 and i = 2, m / 2 is 2, which is the amount of occurrence of the factor 2 inside the 5!. Then m / 2 / 2, which is 1, is the amount of occurrence of the factor 2 * 2 == 4 inside the 5!. Then m / 2 / 2 == 0 is the count for 2 * 2 * 2 == 8, which causes the loop to end due to the 0 encounter.
Edit
I fixed something important in the code, removed the outermost while which was there for nothing, something I had put as I started and apparently forgot to remove, causing potential infinite-loops. Here I also made an improved version of the function that generally runs faster than the one above:
#include <stdio.h>
// this function basically compares the powers of the
// prime divisors of factee and divisor
// ... returns 1 if the powers in divisor are
// ... less than or equal to the powers in factee
// ... returns 0 otherwise
int divides( long factee, long divisor ){
int amount;
if ( divisor % 2 == 0 ){
amount = 0;
int copy = factee;
while ( divisor % 2 == 0 ){
if ( !amount ){
copy /= 2;
if ( !copy )
return 0;
amount += copy;
}
amount--;
divisor /= 2;
}
if ( divisor == 1 )
return 1;
}
for ( int i = 3; i <= factee; i += 2 ){
if ( divisor % i )
continue;
amount = 0;
int copy = factee;
while ( divisor % i == 0 ){
if ( !amount ){
copy /= i;
if ( !copy )
return 0;
amount += copy;
}
amount--;
divisor /= i;
}
if ( divisor == 1 )
return 1;
}
return 0;
}
int main( ) {
printf( "%d", divides( 34534564, 345673455 ) );
//printf( "%d", divides( 20, 10000 ) );
getchar( );
return 0;
}
long can support a value in the range of -2,147,483,647 to 2,147,483,647, here 2000000! is out of the range of long, that is why it is showing error.