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.
Related
For my homework, I am trying to code a calculator which can also calculate average of taken numbers. I don't want to ask for number of numbers because our teacher don't want it in that way. So I thought of scanning values until the user presses "p". But as you would guess, the numbers are float and "p" is a character. What I want to do is assigning the value scanned to both of them if it is possible. I tried different ways, played with the codes but it isn't working properly. So I am seeking your advice.
It prints a value when p is inputted as like 3rd, 5th, 7th (oddth) number (sometimes right, sometimes wrong but I can fix it if I figure this out). But it doesn't print a value in other occasions and expects infinite inputs from the user.
This is the code I have written for this. scanf("%f %c", &number1, &pause); command is where I want to know about, actually.
#include<stdio.h>
float number1, number2, i, result;
char pause;
int main() {
scanf("%f", &number1);
i = 0;
while (pause != 'p') {
number2 = number1 + number2;
scanf("%f %c", &number1, &pause);
i++;
}
result = number2 / (i - 1);
printf("%f", result);
}
Use double not floats if there is no specific reason to do so (like using uC without double FPU).
You do not initialize the variables
Always check the result of the I/O operation.
#include <stdio.h>
int main ()
{
double number1= 0, number2 = 0, i = 0, result = 0;
char pause = 0;
char line[128];
while (pause != 'p')
{
if(fgets(line, sizeof(line), stdin))
{
if(sscanf(line, "%lf %c",&number1, &pause) != 2)
{
printf("Wrong input - try again\n");
pause = 0;
continue;
}
number2 = number1 + number2;
i++;
}
else
{
// do something with I/O error
}
}
result = number2 / (i-1);
printf("%lf",result);
}
You can play with it yourself : https://onlinegdb.com/Hy3y94-3r
I noticed 3 problems with your code.
First I would advise you to use meaningful variables names. number1, number2, etc. and the i which represents the number of inputs given can be an int instead of a float.
Secondly, you lack of printing to the user what's going on in your program; it's better to have messages like "enter your number, do you wanna stop? the result is...etc".
Lastly, having two inputs in one line of code can make it hard to debug, knowing that reading strings and characters in C is already hard for beginners. For example, %c does not skip whitespace before converting a character and can get newline character from the previous data entry.
Here is my fix: I changed some variables' names, printed some messages and read the two inputs in two different lines with adding scanf(" %c") with the space to avoid that problem.
#include<stdio.h>
float sum, temp, result;
int nb;
char pause;
int main () {
pause='a';
while (pause != 'p'){
printf("Enter your number: ");
scanf("%f",&temp);
sum+=temp;
nb++;
printf("type 'p' if you want to stop: ");
scanf(" %c",&pause);
}
result = sum / nb;
printf("the average is : %f",result);
}
I tested it, should work fine
Edit: after explaining that you don't want to ask the user each time, here is how the code should work (the case that the user don't input a float is not treated, and just take it as zero
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
float sum, temp, result;
int nb;
char input[50];
int main () {
sum=0;
nb=0;
printf("Enter your numbers, then type 'p' to stop\n");
do{
printf("Enter your next number: ");
scanf("%s", input);
if(strcmp(input,"p")!=0)
{
float temp= atof(input);
sum+=temp;
nb++;
}
}while(strcmp(input,"p")!=0);
if(nb!=0)
result = sum / nb;
printf("\nThe average is : %f",result);
}
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
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 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.