cs50 pset 1 cash only prints out zeros - cs50

I tried figuring out what the problem was with my code, i checked if the brackets were ok, but i still cant figure it out.this is pset 1 cash
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
{
float dollars;
int cents = 0;
int coin_amount = 0;
do
{
//prompt user for amount of change
dollars = get_float("change: ");
}
while (cents < 0);
cents = round(cents * 100);
while (cents >= 25)
{
cents = cents - 25;
coin_amount++;
}
while (cents >= 10)
{
cents = cents - 10;
coin_amount++;
}
while (cents >= 5)
{
cents = cents - 5;
coin_amount++;
}
while (cents >= 1)
{
cents = cents - 1;
coin_amount++;
}
printf("%d\n",coin_amount);
}
Input: 1 dollar
Expected Output:4 coins

Your bug is that you say cents = round(cents * 100) when you really meant to say cents = dollars * 100
It is difficult to read the code because of the lack of consistent indenting, but your first do while loop also isn't working properly. It checks the value of cents but you don't actually try to convert from dollars to cents until after you're out of the loop. In other words, the do-while loop will only ever be run exactly once. You could put a negative number into it and break the program's intent. You need to convert to cents within that loop. If this works, appreciate the upvote.

Related

CS50 llamas lab I don't know how to solve it

#include <cs50.h>
#include <stdio.h>
int main(void)
{
int start ;
do
{
start = get_int("start size: ");
}
while (start < 9);
int end;
do
{
end = get_int("end size: ");
}
while (end < start);
int year = 0;
do
{
start = start + (start / 3) - (start / 4);//calculate number of years untile we reach thresholă…‡
**year++;**
}
while (start < end);
printf("Years: %i", year);
}
enter image description here
:( handles same starting and ending sizes
expected "Years: 0", not "Years: 1"
i think year++ is the problem i don't know how to solve it
Remember, the do loop will execute the body and then test the condition (in the while). When start and end are both 100, year will be incremented before it evaluates the while condition. Since program needs to compare start and end before it increments year, a simple while loop is appropriate.

pset2 readability always printing before grade 1 no matter what input

I know this is a fairly newbie question so I'm sorry if the solution is painfully obvious to you guys.
I've fully coded up pset 2 readability and it worked for printing out the number of letters, words and sentences for the user inputted text- I have since removed those print statement as they aren't needed for the pset (I just wanted to actually make sure the functions were returning something- they worked just fine).
I'm up to printing out the grade level now but no matter what text I input I only get before grade 1. I've already checked to see if I had anything wrong with my print statements and I can seem to find an issue there so I'm thinking that there may be an error in the calculation of the grade level itself- I've looked until my eyes have gone square and for the life of me I can not see anything wrong.
If someone could shed some light on my problem I would love to be saved the headache :), or even point me in the right direction so I get the learning. (also first time poster, long time lurkers so forgive me if anything is formatted incorrectly).
Thank you all!
Here is my code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
// my functions to calculate letters, words
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int main(void)
{
string text = get_string("Text: ");
int letters = count_letters(text);
int words = count_words(text);
int sentences = count_sentences(text);
float calculation = (0.0588 * letters / words * 100) - (0.296 * sentences / words *
100) - 15.8;
int index = round(calculation);
if (index < 1)
{
printf("Before grade 1.\n");
}
else if (index >= 16)
{
printf("Grade: 16+.\n");
}
else
{
printf("Grade: %i.\n", index);
}
}
int count_letters(string text)
{
int letters = 0;
for (int i = 0; i < strlen(text); i++)
//((text[i] > 65 && text[i] < 90) || (text[i] > 97 && text[i] < 122))
if (isalpha(text[i]))
{
letters++;
}
return letters;
}
int count_words(string text)
{
int words = 0;
for (int i = 0; i < strlen(text); i++)
if isspace ((text[i]))
{
words++;
words = words + 1;
}
return words;
}
int count_sentences(string text)
{
int sentences = 0;
for (int i = 0; i < strlen(text); i++)
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentences++;
}
return sentences;
}
I just wanted to actually make sure the functions were returning something- they worked just fine
Yes, the functions return "something" but is it the right thing? Suggest you add back the debug printf and look at the results carefully and critically. Start with the simplest text ("One fish. Two fish. Red fish. Blue fish."). 29 letters, 8 words, 4 sentences. What result is printed?
Inside of the function count_words
you have an if statement, if statements need to have brackets, the line wouldn't make sense even if you had the brackets, so double-check the logic as well.

running programme in parallel using fork()

I am trying to complete a tutorial on running a parallel programme in C using fork() and execl commands.
The user enters the number of inputs(N). The next N lines contain a number <= 10 digits. My programme will calculate the number of prime factors for each digit.
I am trying to make the execution of the lines parallel using fork and execl.
Parallel.c
int main() {
int userInput, childPid, childResult, number;
//Since largest number is 10 digits, a 12 characters string is more
//than enough
char cStringExample[12];
scanf("%d", &userInput);
for (int i = 0; i < userInput; i++) {
scanf("%d",&number);
childPid = fork();
if (childPid == 0) {
sprintf(cStringExample,"%d",number);
execl("./PF","PF",cStringExample,NULL);
}
}
while (wait(&childResult) != -1) {
printf("%d has %d prime factors\n",number,childResult >> 8);
}
}
PrimeFactorization.c
int main( int argc, char* argv[]) {
int nFactor = 0, userInput, factor;
//Convert string to number
userInput = atoi( argv[1] );
nFactor = 0;
factor = 2;
//quick hack to get the number of prime factors
// only for positive integer
while (userInput > 1){
if (userInput % factor == 0){
userInput /= factor;
nFactor++;
} else {
factor++;
}
}
// printf("%d has %d prime factors\n",userInput,nFactor);
return nFactor;
}
I want to be able to print for each forked() process the number that was inputted into the Prime Factorisation programme as well as the number of prime factors for it.
For example if I input
5
44721359
99999989
9
111113111
118689518
the output is
118689518 has 2 prime factors
118689518 has 3 prime factors
118689518 has 1 prime factors
118689518 has 1 prime factors
118689518 has 1 prime factors
The prime factors are correct just that it does not correspond to the number that has been inputted. How am I able to do that? I tried to insert the wait command inside the for loop but I don't think that produces parallelism. I understand why it gives me the output but I can't think of a solution for it.

Counter for two binary strings C++

I am trying to count two binary numbers from string. The maximum number of counting digits have to be 253. Short numbers works, but when I add there some longer numbers, the output is wrong. The example of bad result is "10100101010000111111" with "000011010110000101100010010011101010001101011100000000111000000000001000100101101111101000111001000101011010010111000110".
#include <iostream>
#include <stdlib.h>
using namespace std;
bool isBinary(string b1,string b2);
int main()
{
string b1,b2;
long binary1,binary2;
int i = 0, remainder = 0, sum[254];
cout<<"Get two binary numbers:"<<endl;
cin>>b1>>b2;
binary1=atol(b1.c_str());
binary2=atol(b2.c_str());
if(isBinary(b1,b2)==true){
while (binary1 != 0 || binary2 != 0){
sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;
remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0){
sum[i++] = remainder;
}
--i;
cout<<"Result: ";
while (i >= 0){
cout<<sum[i--];
}
cout<<endl;
}else cout<<"Wrong input"<<endl;
return 0;
}
bool isBinary(string b1,string b2){
bool rozhodnuti1,rozhodnuti2;
for (int i = 0; i < b1.length();i++) {
if (b1[i]!='0' && b1[i]!='1') {
rozhodnuti1=false;
break;
}else rozhodnuti1=true;
}
for (int k = 0; k < b2.length();k++) {
if (b2[k]!='0' && b2[k]!='1') {
rozhodnuti2=false;
break;
}else rozhodnuti2=true;
}
if(rozhodnuti1==false || rozhodnuti2==false){ return false;}
else{ return true;}
}
One of the problems might be here: sum[i++]
This expression, as it is, first returns the value of i and then increases it by one.
Did you do it on purporse?
Change it to ++i.
It'd help if you could also post the "bad" output, so that we can try to move backward through the code starting from it.
EDIT 2015-11-7_17:10
Just to be sure everything was correct, I've added a cout to check what binary1 and binary2 contain after you assing them the result of the atol function: they contain the integer numbers 547284487 and 18333230, which obviously dont represent the correct binary-to-integer transposition of the two 01 strings you presented in your post.
Probably they somehow exceed the capacity of atol.
Also, the result of your "math" operations bring to an even stranger result, which is 6011111101, which obviously doesnt make any sense.
What do you mean, exactly, when you say you want to count these two numbers? Maybe you want to make a sum? I guess that's it.
But then, again, what you got there is two signed integer numbers and not two binaries, which means those %10 and %2 operations are (probably) misused.
EDIT 2015-11-07_17:20
I've tried to use your program with small binary strings and it actually works; with small binary strings.
It's a fact(?), at this point, that atol cant handle numerical strings that long.
My suggestion: use char arrays instead of strings and replace 0 and 1 characters with numerical values (if (bin1[i]){bin1[i]=1;}else{bin1[i]=0}) with which you'll be able to perform all the math operations you want (you've already written a working sum function, after all).
Once done with the math, you can just convert the char array back to actual characters for 0 and 1 and cout it on the screen.
EDIT 2015-11-07_17:30
Tested atol on my own: it correctly converts only strings that are up to 10 characters long.
Anything beyond the 10th character makes the function go crazy.

Vigenere.c CS50 Floating Point Exception (Core Dumped)

I am working on the Vigenere exercise from Harvard's CS50 (in case you noticed I'm using string and not str).
My program gives me a Floating Point Exception error when I use "a" in the keyword.
It actually gives me that error
when I use "a" by itself, and
when I use "a" within a bigger word it just gives me wrong output.
For any other kind of keyword, the program works perfectly fine.
I've run a million tests. Why is it doing this? I can't see where I'm dividing or % by 0. The length of the keyword is always at least 1. It is probably going to be some super simple mistake, but I've been at this for about 10 hours and I can barely remember my name.
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (int argc, string argv[])
{
//Error message if argc is not 2 and argv[1] is not alphabetical
if (argc != 2)
{
printf("Insert './vigenere' followed by an all alphabetical key\n");
return 1;
}
else if (argv[1])
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (isalpha((argv[1])[i]) == false)
{
printf("Insert './vigenere' followed by an all alphabetical key\n");
return 1;
}
}
//Store keyword in variable
string keyword = argv[1];
//Convert all capital chars in keyword to lowercase values, then converts them to alphabetical corresponding number
for (int i = 0, n = strlen(keyword); i < n; i++)
{
if (isupper(keyword[i])) {
keyword[i] += 32;
}
keyword[i] -= 97;
}
//Ask for users message
string message = GetString();
int counter = 0;
int keywordLength = strlen(keyword);
//Iterate through each of the message's chars
for (int i = 0, n = strlen(message); i < n; i++)
{
//Check if ith char is a letter
if (isalpha(message[i])) {
int index = counter % keywordLength;
if (isupper(message[i])) {
char letter = (((message[i] - 65) + (keyword[index])) % 26) + 65;
printf("%c", letter);
counter++;
} else if (islower(message[i])) {
char letter = (((message[i] - 97) + (keyword[index])) % 26) + 97;
printf("%c", letter);
counter++;
}
} else {
//Prints non alphabetic characters
printf("%c", message[i]);
}
}
printf("\n");
return 0;
}
}
This behavior is caused by the line keyword[i] -= 97;, there you make every 'a' in the key stream a zero. Later you use strlen() on the transformed key. So when the key starts with an 'a', keywordLength therefor is set to zero, and the modulo keywordLength operation get into a division by zero. You can fix this by calculating the keyword length before the key transformation.

Resources