I'm trying to write a c program that uses a function that adds 2 integers to a random number. Which I have accomplished below. My problem is, I set a variable to a secret number and when that number is found, I need the program to terminate and it does not.
int x,y,secretnumber;
secretnumber = 5;
do
{
printf("Please enter two integers to be added together to a random number from 0-99 \n"
"Keep entering numbers until you hit the secret number!\n");
scanf("%i%i", &x, &y);
if(sumintsrand(x,y) != secretnumber)
{
printf("The summation of integers %i and %i and a random number is %i \n\n",x,y,sumintsrand(x,y));
}
else
{
printf("You have found the secret number: %i! Goodbye!\n", secretnumber);
}
}
while(sumintsrand(x,y) != secretnumber);
return 0;
}
int sumintsrand(int x, int y)
{
int sumintsrand = x + y + rand()%5;
return sumintsrand;
}
If anyone has any idea where I'm going wrong I would really appreciate it
UPDATE
I compiled your program with my earlier suggested mod, and I didn't get silly large numbers, so pass on that - different question?
It seems a bit strange to keep changing the random number - the same guess might fail once but work the next time. Also there is a confusion about whether the range is 5 or 99.
So I've simplified your work, to make you guess two numbers that sum to the secret number. If that's not your intention, perhaps you can draw on my code.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAXVAL 5
int main(){
int x, y, secretnumber, testval;
srand ((unsigned)time(NULL));
secretnumber = rand() % (MAXVAL+1);
do
{
printf("Enter two integers to be added to equal a secret random number from 0-%d\n"
"Keep entering numbers until you hit the secret number!\n", MAXVAL);
if (scanf("%d%d", &x, &y) != 2)
return 0; // exit program
testval = x + y;
if(testval != secretnumber)
printf("Sorry - try again!\n\n");
else
printf("You have found the secret number: %d + %d = %d! Goodbye!\n",
x, y, secretnumber);
}
while(testval != secretnumber);
return 0;
}
You are calling your sumintsrand() function thrice. Each time, the result of the function is going to be different based on what rand() returns.
Your call to sumintsrand()within the while loop may have found the secret number, but that is not retained. You need to store it for checking whether while loop needs to be terminated.
UPDATE:
int sum = 0;
do {
scanf("%i%i", &x, &y);
sum = sumintsrand(x,y);
} while(sum != secretnumber);
It's not working, because in that line while(sumintsrand(x,y) != secretnumber); you are calling sumintsrand a second time - and it gives other result.
Possible solutions:
Save the result of first call of sumintsrand and check if it(the saved result) is the same as secretnumber
Use break
Make bool variable which will end the loop - at the beginning it will be true, when you will find the number just set it to false.
Related
I am learning how to use "rand()" and "srand()" in C. In the book that I am reading, it asks to modify a program that generates random numbers so that the user supplies a seed. This ensures the numbers are random. I am able to generate new numbers using the basic code directly below, but it will not work when I try to use it within the program beneath it.
int main()
{
int seed;
srand(seed);
printf("Please enter a seed: ");
scanf("%d", &seed);
printf("The random number is: %d\n", rand());
return (EXIT_SUCCESS);
}
Here is the program I am having trouble getting "srand() to work in below. I have tried asking the user for the seed in "main", rather than the prn_random_numbers function and everything else I could think of. It still only behaves like "rand()" and spits out the same number regardless of the seed that I enter. What am I doing wrong? Unfortunately, the book doesn't give any answers to the exercises. I greatly appreciate any help. I am just learning on my own.
max(x, y)
int x, y;
{
if (x > y)
return (x);
else
return (y);
}
min(x, y)
int x, y;
{
if (x < y)
return (x);
else
return (y);
}
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
int seed;
srand(seed);
printf("Please enter a seed: ");
scanf("%d", &seed);
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
Part 1
In the first block of code, you call srand() with an uninitialized variable — this is not good. You need to move that call after where you read the seed from the user. You should also check that you got a valid result from the input.
int main(void)
{
int seed;
printf("Please enter a seed: ");
if (scanf("%d", &seed) != 1)
{
fprintf(stderr, "Failed to read seed - exiting\n");
return EXIT_FAILURE;
}
srand(seed);
Part 2
In the second block of code, you are writing K&R-style function definitions.
DON'T!!!
And yes, I would shout louder if I could. If your text book is teaching you this style, hurl the book into the rubbish bin and get another book. You have to have an extraordinary reason to use K&R-style definitions in new code. Prototypes have been available via standard compilers for about thirty years now, and have been generally available everywhere for twenty years.
Your code calling srand() in the second example also has the same flaw as in the first — calling the function before you get a seed from the user.
Also, the chances of users giving a different seed each time the program is run are approximately nil. Your claim that it "ensures the numbers are random" is a very optimistic view.
I am new to c ,while i am writing a basic program in c ,it is showing two answers ..1)when i declare and intialize variables separately 2)when I declare and initialize variable in a same line.can any one tell me my mistake please?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
I am getting 2 as answer when i gave 3 and 4 as inputs
scanf("%d", &x) will store the read number into x. It will return the number of successfully read fields (1 in your case). If you assign that return value to x afterwards, you overwrite whatever the user entered with that 1. And 1 + 1 produce 2.
Solution:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
As David reminds in comments, you might want to check that all fields were read successfully. For example, in your case, if you enter a non-digit, scanf will not resolve the %d field as successful, and will return 0. You can test this result to make sure the user did what they were supposed to do:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}
scanf() function returns 1 if it scan successfully otherwise it return 0. That's why when you put an integer to x, scanf() return 1 and assign it to x(x=1). Same for y(y=1).
As x=1 and y=1.
sum = 2
I'm writing a c program for my intro class and I'm stuck on the if/else statements. we have to output the highest,lowest grade entered as well as the avg for those. Marks entered must be between 0-100. this is my code so far, i can't seem to figure it out, thanks for any advice! :
#include <stdio.h>
int main (void)
{
int numberofMarks;
int i;
int x;
int y;
int numofPasses=1;
int numofFails=1;
float sumpassedMarks =0;
float sumfailedMarks=0;
float markEntered=0;
float highestMark=0;
float lowestMark=0;
float totalMark=0;
float avgofMarks=0;
float avgpassedMarks=0;
float avgfailedMarks=0;
printf (" ---=== IPC mark Analyser ===---\n");
printf ("Please enter the number of marks(between 3 and 40): ");
scanf ("%d", &numberofMarks);
//asks user for number of marks, only takes 3-40, otherwise outputs error msg
for (i=1 ; (numberofMarks < 3)||(numberofMarks > 40) ; i++) {
printf ("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf ("%d", &numberofMarks);
}
//for loop recieves the mark
for (x=1 ;(x <= numberofMarks) ; x++) {
printf ("%d> ", x);
scanf ("%f", &markEntered);
//contd loop..loop makes sure mark entered is between 1-100
for (y=1; (markEntered <0)||(markEntered>100); y++)
{
printf ("Error, Enter values between 0 and 100 incluisve.\n");
printf ("%d> ", x);
scanf ("%f", &markEntered);
if (markEntered >= 50) {
numofPasses=numofPasses+1;
}
if else (markEntered <= 49) {
numofFails = numofFails+1;
}
if else (markEntered > highestMark) {
highestMark = markEntered;
}
else (markEntered < lowestMark) {
lowestMark = markEntered;
}
}
//adds the mark entered to all the marks entered for a overall sum
totalMark = totalMark + markEntered;
}
avgofMarks = (float)totalMark / numberofMarks;
avgpassedMarks = (float)sumpassedMarks / numberofMarks;
avgfailedMarks = (float)sumfailedMarks / numberofMarks;
printf ("Total of %d students passed with an average of %.1f.\n", numofPasses,avgpassedMarks);
printf ("Total of %d students failed with an average of %.1f.\n", numofFails, avgfailedMarks);
printf ("Highest mark in the group: %.1f\n", highestMark);
printf ("lowest mark in the group: %.1f\n", lowestMark);
printf ("The average of all marks in this group is %.1f.\n", avgofMarks);
printf ("Program Ended.\n");
return 0;
}
The work asks,
In the loop in which marks are being entered, after each entry examine the value of the mark entered:
If it is a pass, add one to the number of passes and add the value of the mark to the sum of passed marks.
If it is a fail, add one to the number of fails and add the value of the mark to the sum of failed marks.
If the value is higher than the highest mark, set highest mark to the value read.
If the value is lower than the lowest mark, set the lowest mark to
the value read. After all the marks are entered and examined, divide
the sums by the corresponding number of marks to get the average and
print the results.
This is my output vs the sample output.
Your code is a mess; let's try to get some things straight here:
If you're not gonna use i in the body of a for loop, no reason to initialize and increment it. Better to use a while.
When you post a question, clear all not-strictly-necessary code from the answer, so that it's easier to help
Instead of making 15 variables, consider using an array or, if you're not gonna use the values later in the program, print the result directly.
Ex.
int a = 10, b = 15; If you wanna print the sum, no reason to save it in a new int sum, just printf("%d", a + b);
Do not request the number of votes outside of a loop, and then loop to verify the value (your first for loop). Consider a DO..WHILE loop instead.
Ex.
do{
scanf("%d", &n);
} while(n <= 0);
//Scan integer and save into n, until you get a positive value
Avoid nesting for loops for no reason, use more if() .. else if() .. if necessary.
It's not the best of practise, but you can also use the continue and break keywords to continue or stop the loops respectively.
Do not use "else" randomly. If you have more conditions to check, leave the if without else. You wanna use else after an if condition if (when the first condition comes back true) you don't want to check the next condition (they will be skipped !)
My program asks the user for a numerator and then a denominator right after (If option 1 is chosen). I am pretty sure i got that part correct.I can not seem to figure out how to display the fraction(s) though when I hit option 2.
This is my code:
#include<stdio.h>
#include<string.h>
typedef struct fraction
{
int numerator, denom;
} fraction; //defined the fraction.
int main()
{//start of program
int z = 0;
int y = 0;
while (1)
{ //start of while loop
int choice;
printf("\nPress 1 to enter a fraction\n");
printf("Press 2 to view the entered fraction\n");
scanf("%d", &choice);
fraction arrFraction[100];
arrFraction[0].numerator = 0;
arrFraction[0].denom = 0;
if (choice == 1) // first option (enter numerator and then denom after)
{
printf("Enter the fraction\n");
scanf("%d", &arrFraction[y].numerator);
scanf("%d", &arrFraction[z].denom);
y++
z++;
}// end of first if statement(to enter the fraction)
if (choice == 2) //to view the entered fractions.
{
printf("\n-----------------------------");
for (int m = 0; m < z; m++)
{
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
}
printf("\n\n-----------------------------");
} // end of second if statement (to view the fraction entered earlier)
} // end of while loop
system("pause");
return(0);
}
You need to move fraction arrFraction[100]; out of while loop, otherwise, every iteration, there will be a new array.
That said,
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
is wrong, you're supplying two format specifiers but one argument. This invokes undefined behavior. Your compiler should have warned you.
I believe, what you want instead is
printf(" %d / %d \n", arrFraction[y].numerator, arrFraction[z].denom);
That said, I'm not very convinced with the overall logic. Why do you seem to need an array of 100 elements? If you're only interested in previous record (not records), use only a simple variable, not an array. Besides, you don;t need to have two separate index/ counters anyway. A single index will be able to manage the inputs in much concise and robust way.
I'm trying to right a program in C where I have to ask the user a certain multiplication question, I'm using rand() to generate the numbers.
If the user gets the answer wrong, then they will be asked to enter it again once they get it right, when they do get it right, the program should loop and ask the user a different question.
I'm using a separate function to generate the answer each time the 2 random values are passed to that function.
My problem is that once I get the answer correct, the program loops and asks the same question, it picks the same number! so how do I make it that everytime it loops, it picks a different number?
#include <stdio.h>
int multiply(int x, int y);
int main()
{
srand (time(NULL));
int x = rand()%20;
int y = rand()%20;
int i, answer;
i = multiply(x,y);
do {
printf("what is %d multiplied by %d?:", x, y);
scanf("%d", &answer);
while(answer != i)
{
printf("wrong try again!");
scanf("%d", &answer);
}
printf("very good!\n");
} while(i==answer);
}
int multiply(int x, int y)
{
int k;
k=x*y;
return k;
}
You need to move the assignments of x and y into the loop. This way they will get a new value in each round. In fact, you can move their whole definition in there.
Moreover, the loop coondition while(i==answer) is superfluous as at that point it is always going to be true. For the sake of clarity, you should replace it with true to make it explicit that it is an infinite loop. (And you may want to extend your program with a way to exit gracefully, e.g. if 'q' or an empty string is entered - but I will leave this as an exercise for you :-).
while(true) {
int x = rand()%20;
int y = rand()%20;
int i, answer;
i = multiply(x,y);
printf("what is %d multiplied by %d?:", x, y);
scanf("%d", &answer);
while(answer != i)
{
printf("wrong try again!");
scanf("%d", &answer);
}
printf("very good!\n");
}
Abstractly, your logic should go like this:
// seed random number generator
while (true) // ask infinitely many questions
{
int x, y, expected_result; // populate randomly
printf("Please compute the result of %d and %d: ", x, y);
while (read_answer() != expected_result)
{
printf("Sorry, wrong answer. Try again: ");
}
}
That is, for each question you generate new parameters.
You just need to implement read_answer() as a helper function that reads one integer from the input, e.g. using fgets and strtol.