I recently enrolled myself into the CS50 class offered by EDx.com. I'm currently having trouble with the greedy.c problem is pset1. I feel like the problem is that my do-while loops aren't actually looping. Regardless of the input I give the program I get 4 coins every time. Please let me know what I'm doing wrong.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int n = 0;
int count = 0;
int cents = 0;
do
{
printf("How much change is owed?\n");
get_int();
}
while(n > 0);
do
{
count++;
n -=25;
}
while(n >= 25);
do
{
count++;
n -=10;
}
while(n >= 10);
do
{
count++;
n -=5;
}
while(n >= 5);
do
{
count++;
n -=1;
}
while(n >=1);
printf("Here is %i coins\n", count);
}
This line in your code:
get_int();
Does nothing.
get_int will get and return an int, however you never actually put that value in a variable, that is the reason the input does not change the program's behavior.
Perhaps you meant to write something like this:
n = get_int();
The do while loops will always execute once that's why you're always getting 4 coins, then you're also not assigning the input value to n.
The first do while will run infinitely if n > 0 so change it to:
do {
printf("How much change is owed?\n");
n = get_int();
} while (n == 0);
next your do whiles will add to count even when they shouldn't, the below should be better.
while (n >= 25) {
count++;
n -= 25;
}
Good luck with CS50, thats where I started as well, it's difficult but really sets you up to learn to think.
Related
So today I am learning the "while" loop in c#,
the task was simple:
you can keep input score between 0~100;
when you in put "-1", the program ends;
it'll output the sum and the average.
here is our teacher's answer:
#include <stdio.h>
int main(void) {
int score = 0;
int sum = 0;
int count = 0;
while(score != -1) {
printf("輸入分數(-1結束):");
scanf("%d", &score);
count++;
sum =sum + score;
}
printf("加總:%d 平均:%f\n",sum+1, (double) sum / count );
return 0;
}
here is my code:
#include <stdio.h>
int main(void)
{
int score = 0;
int sum = 0;
int count = -1;
while ( score > 0 || score <=100)
{
printf("輸入一個介於0~100的整數(-1結束):");
scanf("%d", &score);
count++;
sum = sum + score;
if ( score == -1)
{
break;
}
}
printf("加總: %d 平均: %f", sum+1, (double)sum / count);
return 0;
}
I know I'm just learning from the beginning,
my teacher said that let's not think too much about the user could input score over 100 or less than -1,
But I just can't help to think about we should first examine whether the input score is within 0~100, if it is then proceed the program,
and then the program will keep asking the user to input more, until the user input -1 and print the result of sum and the average.
so that's why I choose to wrote
while ( x >= 0 || x <= 100)
I can't figure out what is missing in the thought process.
Am I thinking the right direction?
How can I better fix the code?
I think you were on the right path, but you did miss something
#include <stdio.h>
int main(void)
{
int score = 0;
int sum = 0;
int count = -1;
while ( 1 )
{
printf("輸入一個介於0~100的整數(-1結束):");
scanf("%d", &score);
if ( score == -1 || score > 100 )
{
break;
}
count++;
sum = sum + score;
}
printf("加總: %d 平均: %f", sum+1, (double)sum / count);
return 0;
}
The important thing is to immediately exit the loop, without using the value of score, if it is not a valid score. Note that the while loop just runs indefinitely. It is only the break that stops looping. Also, note the logic in the if statement: we want to exit if the value is too low OR too high. This is the opposite of the way you'd written the code, because you wanted the loop to continue as long as the value was less than 100 AND more than -1.
You need to update your while loop condition.
while (score > 0 && score <= 100)
This is C code not C#
you can try this:
int main()
{
int score;
do {
printf("Enter a number between 0 and 100: ");
scanf("%d", & score);
} while (score > 0 && score <=100);
return 0;
}
I am self learner, I am working on a population growth problem, and I came across the issue of loop running infinitely when I enter a big ending number that I want to reach.
#include <cs50.h>
#include <stdio.h>
int main(void) {
// TODO: Prompt for start size
int n;
do {
n = get_int("Enter the starting size of your llamas: ");
} while (n <= 8);
// TODO: Prompt for end size
int j;
do {
j = get_int("Enter the Ending size of your llamas: ");
} while (j <= n);
// TODO: Calculate number of years until we reach threshold
int k = 0;
do {
n = n + (n/3) - (n/4);
printf("The number is %i\n", n);
k++;
} while (n != j);
// TODO: Print number of years
printf("The number is %i\n", k);
}
The answer is supposed to be the number of years it takes to reach the end size llamas, but I am not able to put in big numbers of end size, can you help me figure out what is wrong, maybe in my math or a sign. Thanks in advance.
For large numbers, n is incremented by more than 1 at each iteration, so it is possible than it becomes larger than j without being equal to it first.
Change the test while(n != j); to while(n < j);
as you saw up there the problem is that the loop does not continue after the users has entered his code, i am wondering why this is and if you have a better purpose for me. I am new to the C language help is much appreciated!!!!!!
#include <stdlib.h>
#include <stdio.h>
int main()
{
int randomNumber = 11;
int usersGuess;
int i;
do {
printf("You need to guess a number between 0 and 20! Good Luck! \n");
for (i = 5; i > 0; i--) {
printf("You have got %d amount of tries, Guess The random number: ", i);
scanf_s("%d", usersGuess);
if (usersGuess == randomNumber) {
printf("You won");
break;
} else if (usersGuess > randomNumber) {
printf("That is wrong, random number is less than that");
} else if (usersGuess < randomNumber) {
printf("that is wrong, the random number is higher than that");
} else if (usersGuess > 20) {
printf("please guess again cause the random number is between 0 and 20");
}
}
} while(i > 0);
return 0;
}
Your code has Undefined Behaviour, which means it's buggy and anything can happen. The problem is that you're passing an integer to scanf_s where it want a pointer. Do this:
scanf_s("%d", &usersGuess);
The reason is that you want the function to write into the variable usersGuess. In C, all parameters are passed by value, so if you want an output parameter, you have to make it a pointer.
In this file I am trying to make something that adds all numbers up to a number entered by a user. Such as, 4: 1 + 2 + 3 + 4 = 10. So if they enter 4 it returns 10.
When I run the code I get an error message saying my file has stopped working. Do i have an endless loop?
#include "biglib.h"
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
// Asking them for their number
int num;
scanf("%i", num);
// then I run a loop, if num == 0 then the program should break from the loop and return 0 in the main function if not run the code inside the program.
int i;
while(num != 0)
{
// I define "i" to be one less than that of num then as long as "i" is greater than 0 keep running the loop and subtract one at the end of it.
for(i = num - 1; i > 0; i--)
{
// in here I do the addition.
num = num + i;
}
// finally I print out the answer.
printf("%i\n",num);
continue;
}
return 0;
}
Yes, you have an infinite loop. Also the input is not stored in the num variable.
#include "stdio.h"
int main(void) {
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
scanf("%i", &num);
int sum = 0;
while(num>0){
sum += num;
num -= 1;
}
printf("%i\n",sum);
return 0;
}
Some lines of your code seem odd to me.
Why do you use a while loop to test the value of num ?
Why do you put a continue statement as last while loop instruction ?
Remarks:
Your code does not work for negative number, is it the expected behaviour?
You are not testing the scanf return value, which could cause trouble.
I am pretty sure that you should check the scanf prototype.
Hope these questions will lead you to improve your code.
Thank you yadras fro informing me that I had the scanf outside of the while loop that was the problem and now it works when I do this.
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
int i;
while(num != 0){
scanf("%i", &num);
for(i = num - 1; i > 0; i--)
{
num = num + i;
}
printf("%i\n",num);
}
return 0;
}
Can someone please help me figure out what is wrong with my program it is prety complex for me. It is a number guessing game where two player can play. It starts by saying which player goes first and the player then has to input his number either 1 or 2 and then enter a guess or either pass (players can't pass more than 3 times or twice in a row). It is working very good except that everytime player 1 starts it asks him for a guess twice in a row bu then works fine, and when player 2 starts it alternates like it should like this:
And this is my code It quite a lot of code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int playerNumber = 0;
int number = 0;
int playerInput = 0;
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;
srand(time(NULL));
playerNumber = 1 + rand() % 2; /* Random number is generated */
srand(time(NULL));
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
printf("\nIt's player's %d turn\n", playerNumber);
printf("Player Number?\n");
scanf("%d", &playerInput);
while (playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (playerA != playerNumber)
playerB = playerNumber;
if (i%2 == 1) {
playerNumber = playerA;
}
else {
playerNumber = playerB;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (playerNumber == playerA){
passB = passB -1;
printf("Player 2 has %d more 'Pass' left!\n", passB);
}
else{
passA = passA -1;
printf("Player 1 has %d more 'Pass' left!\n", passA);
}
}
else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is to low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is to high */
printf("Your guess was to high.\n ");
else /* is the guess is equial to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}
First of all, you should use consistent indentation. That will make it easier to read your code.
Second, you should use newlines and whitespace to group like-lines together. Think of writing code like writing prose, and newlines as ways to separate paragraphs. You don't double-space almost anything, because it wastes space and is harder to read (people aren't used to it) so don't double-space your code.
Third, your use of the playerA and playerB variables is an OK concept, but there are better ways to do it. The typical convention in C/C++ is to use a #define for magic numbers, with all caps - #define PLAYER_A 1. Following this convention will make your code more readable. Also, since your players are "1" and "2" it is more readable to use #define PLAYER1 1 or PLAYER_1.
You use the variable "i" but the convention for using variables named i, j, k, m, or n is as loop counters that are incremented either at the top of the loop or at the bottom of the loop. Incrementing the loop counter in the middle of the loop makes it much easier for the counter to get lost. Move the increment to the top or the bottom.
Do the work by hand to see what your variables are as the program executes. Your teacher has done this in class. Just write down each variable and write its value next to it, then change the variables as they will change while the program executes. This technique will help you fix other difficult bugs in the future, rather than me giving you the answer.
You have an infinite loop in your code,
your code given below is wrong,
while(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
It should be,
if(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}