I am having problems with the while function on the C programming language. It runs too many times, Ignoring the end condition.
#include <stdio.h>
int main()
{
long long int lenX,lenY,cube,needX,needY,i,t = 0;
scanf("%lld%lld%lld", &lenX,&lenY,&cube);
while (needX <= lenX)
{
needX + cube;
i++;
}
while (needY <= lenY)
{
needY + cube;
t++;
}
printf("%lld\n",i*t);
return 0;
}
When inputting 6 6 4(the answer should be 4) the output ranges from -8519971516809424873 to 0.
I'm sorry if I missed something obvious. I'm new to the C programming language
EDIT: It doesn't care about the numbers
#include <stdio.h>
int main()
{
long long int lenX,lenY,cube,needX,needY;
scanf("%lld%lld%lld", &lenX,&lenY,&cube);
while (needX*cube <= lenX)
{
needX = 574973;
}
while (needY*cube <= lenY)
{
needY = 4057348;
}
printf("%lld %lld %lld\n",needX*needY,needX,needY);
return 0;
}
Still outputs:409600 100 4096
These expression statements
needX + cube;
and
needY + cube;
have no effect.
It seems you mean
needX += cube;
and
needY += cube;
Pay attention to that the variables needX, needY i were not initialized that results in undefined behavior..
This declaration
long long int lenX,lenY,cube,needX,needY,i,t = 0;
initializes to zero only the variable t.
You need to rewrite the declaration at least like
long long int lenX,lenY,cube,needX = 0,needY = 0,i = 0,t = 0;
Related
I have a perfect running code, BUT one criteria for this homework is that it has atleast two different functions. How can i devide this code into one more functions?
I want to sort the alarmClock() function into more functions. There's alot going on in there. Maybe a updateTime() function. I tried something like this but this doesn't work:
#include <stdio.h>
void alarmClock(int, int);
void updateTime(int, int, int);
int main() {
int present_time;
int time_for_alarm;
printf("Time indicates in HHMMSS! \nPresent time: ");
scanf("%d", &present_time);
printf("Time for alarm: ");
scanf("%d", &time_for_alarm);
if (present_time == time_for_alarm)
printf("ALARM!");
else
alarmClock(present_time, time_for_alarm);
return 0;
}
void alarmClock(int presT, int alarmT) {
int presentHH = presT / 10000;
int presentMM = (presT / 100) % 100;
int presentSS = presT % 100;
int combineTime;
while (presT != alarmT) {
printf("%02d:%02d:%02d \n", presentHH, presentMM, presentSS);
presentSS++;
updateTime(presentHH, presentMM, presentSS);
combineTime = presentHH * 100 + presentMM;
presT = combineTime * 100 + presentSS;
}
printf("ALARM!");
}
void updateTime(int presentHH, int presentMM, int presentSS) {
if (presentSS > 59) {
presentSS = 0;
presentMM++;
if (presentMM > 59) {
presentMM = 0;
presentHH++;
if (presentHH > 24) {
presentHH = 1;
}
}
}
}
My teacher hinted me saying "you could make on printTime() function and one updateTime() function sending present_time as arguments". But i dont know how...
This is my working code that needs atleast one more function.
#include <stdio.h>
void alarmClock(int, int);
int main() {
int present_time;
int time_for_alarm;
printf("Time indicates in HHMMSS! \nPresent time: ");
/ scanf("%d", &present_time);
/
printf("Time for alarm: ");
scanf("%d", &time_for_alarm);
if (present_time == time_for_alarm)
printf("ALARM!");
else
alarmClock(present_time, time_for_alarm);
return 0;
}
void alarmClock(int presT, int alarmT) {
int presentHH = presT / 10000;
int presentMM = (presT / 100) % 100;
int presentSS = presT % 100;
int combineTime;
while (presT != alarmT) {
printf("%02d:%02d:%02d \n", presentHH, presentMM, presentSS);
presentSS++;
if (presentSS > 59) {
presentSS = 0;
presentMM++;
if (presentMM > 59) {
presentMM = 0;
presentHH++;
if (presentHH > 24) {
presentHH = 1;
}
}
}
combineTime = presentHH * 100 + presentMM;
presT = combineTime * 100 + presentSS;
}
printf("ALARM!");
}
The working code gives this output (correct output);
if present_time = 115957
and time_for_alarm = 120001
output is
11:59:57
11:59:58
11:59:59
12:00:00
ALARM
but when i created the updateTime() function the code keeps running forever if i have these values:
if present_time = 115957
and time_for_alarm = 120001
output is
11:59:57
11:59:58
11:59:59
11:59:60
11:59:61
11:59:62
11:59:63
... and so on and on (presentSS keeps going +=1 forever)
The variables presentHH, presentMM, and presentSS in the function updateTime are distinct from the ones in alarmClock, so changes to those variables in updateTime are not visible in the calling function.
You need to pass the address of each of these variables and dereference those pointers in updateTime. Then you're actually changing the variables defined in alarmClock.
So change the definition of updateTime to:
void updateTime(int *presentHH, int *presentMM, int *presentSS);
And call it like this:
updateTime(&presentHH, &presentMM, &presentSS);
You'll also need to change the body of updateTime to reflect that the parameters are now pointers and to dereference them. I'll leave that as an exercise to the reader.
dbush shows a good way to solve the problem with not many changes to the general structure. I would suggest a different approach to the task. Instead of passing the addresses of these values, you could restructure your code to pass the composite time and return the updated time. Similiar to this
int updateTime(int presT){
//seperate, update and combine the time value
return updatedTime;
}
this would reduce the interface and would also enable you to write even more functions that can be reused. As you now will have to seperate and combine the time in updateTimeand alarmClock you can write functions that do this instead of writing the same code twice.
example:
int getHours(int time){
return time / 10000;
}
and:
int combineTime(int hours, int minutes, int seconds){
combinedTime = (presentHH * 100 + presentMM)* 100 + presentSS;
return combinedTime;
}
This will help you get more expierience with functions and also helps to let you see one big benefit of functions (having reusable code).
I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}
This is the code:
#include <stdlib.h>
#include <stdio.h>
#include "descartes.h"
/*
* Eulidean travelling salesman
*/
#define MAXCITIES 100
#define FALSE 0
#define TRUE 1
point_t city [MAXCITIES];
int numCities = 0;
int ReadCities(void);
double TourLength(lineSeg_t cityLines[]);
void DrawTour(void);
int main(void) {
printf ("main1\n");
OpenGraphics();
printf ("main2\n");
ReadCities();
DrawTour();
double TourLength(lineSeg_t cityLines[]);
CloseGraphics();
return EXIT_SUCCESS;
}
int ReadCities(void) {
printf ("ReadCities1");
int i = 1;
printf ("ReadCities2");
city[0] = GetPoint();
while ((XCoord(city[i])) >= 0) {
city[i] = GetPoint();
printf ("(%d, %d)", XCoord(city[i]), YCoord(city[i]));
numCities++;
i++;
}
if (numCities <= MAXCITIES) {
return TRUE;
}
else {
return FALSE;
}
}
double TourLength(lineSeg_t cityLines[]) {
double totLen = 0;
int i;
for (i = 0; i < (numCities - 1); i++) {
totLen += Length(cityLines[i]);
}
return totLen;
}
void DrawTour(void) {
lineSeg_t cityLines[MAXCITIES];
int i;
for (i = 0; i < (numCities - 1); i++) {
cityLines[i] = LineSeg(city[i], city[i + 1]);
DrawLineSeg(cityLines[i]);
}
}
When I run the program it prints:
main1
main2
Then the program hangs. I would at least expect it to call ReadCities() and at get as far as printing
ReadCities1
ReadCities2
but no matter what I try it just hangs with a flashing cursor in the terminal after printing main2. There might also be other mistakes in the code but I can't even get far enough to test it out!
Sorry if it's something obvious, i'm new to programming!
Cheers!
Not really sure what this line:
while ((XCoord(city[i])) >= 0)
Is returning, seems this loop might not be breaking. In a situation like this I'd printf() the value ofo XCoord(city[i]) within my loop to see what value is actually in there...
Using printf()'s can be quite useful for things like this.
Also, as someone said there's a function prototype declaration in main:
double TourLength(lineSeg_t cityLines[]);
I am having trouble with this code. In particular I can't seem to figure out why it is that the voteFractions() function doesn't work for me. It gets called appropriately, and all the correct parameters seem to reach the function, but I cannot get anything from "candidates[i].votes_fraction = candidates[i].votes/total;". All I ever get for candidates[i].votes_fraction is 0.00.
I tried running the program with NUMBER_OF_CANDIDATES = 1, and everything runs OK when that is the case, so I feel like I may be doing something silly, but I just can't seem to see it...
#define NUMBER_OF_CANDIDATES 10
typedef struct candidate{
char name[20];
int votes;
float votes_fraction;
} candidate;
int totalVotes(candidate *candidates)
{
int total = 0;
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
total += candidates[i].votes;
return total;
}
void voteFractions(candidate *candidates, int total, char *winner)
{
float most_votes = 0, test;
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
{
candidates[i].votes_fraction = candidates[i].votes/total;
if (candidates[i].votes_fraction > most_votes)
{
most_votes = candidates[i].votes_fraction;
strcpy(winner, candidates[i].name);
}
}
}
int main()
{
candidate candidates[NUMBER_OF_CANDIDATES];
int total;
char winner[20];
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
{
printf("Enter candidate's name and the number of votes received: ");
scanf("%s %d", candidates[i].name, &candidates[i].votes);
}
total = totalVotes(candidates);
voteFractions(candidates, total, winner);
return 0;
}
The problem is that in this statement
candidates[i].votes_fraction = candidates[i].votes/total;
expression
candidates[i].votes/total
uses integer arithmetic because the both operands have type int. As total is always greater than or equal to candidates[i].votes then the result of the division is equal to 0. You have to write
( float )candidates[i].votes/total
Take into account that variable test is declared but not used in function voteFractions. You may remove it.
void voteFractions(candidate *candidates, int total, char *winner)
{
float most_votes = 0, test;
//...
UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}