Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need some help with my simple calculator program. It seems to work fine until I use the * symbol for multiplication. When I use the * symbol it comes out to be 99 instead of the ASCII equivalent of 42. The arguments it expects are an integer, operator(+ ,-, *, /) and another integer.
#include <stdio.h>
#include <stdlib.h>
/*
void usage() {
printf("This is a calculator program, just put in to numbers and and operator\n");
printf("Example:\n\t2 + 2\n");
}
*/
int main(int argc, char *argv[]) {
int first_number, second_number;
int symbol;
int sum;
first_number = atoi(argv[1]);
second_number = atoi(argv[3]);
symbol = (int)*argv[2];
printf("symbol varable = %d\n", symbol); // debugging for argv[2]
if (symbol == 43 ) {
sum = first_number + second_number;
printf("sum = %d\n", sum);
}
else if (symbol == 45 ) {
sum = first_number - second_number;
printf("sum = %d\n", sum);
}
else if (symbol == 42) {
sum = first_number * second_number;
printf("sum = %d\n", sum);
}
else if (symbol == 47) {
sum = first_number / second_number;
printf("sum = %d\n", sum);
}
return 0;
}
The problem has nothing to do with your code.
When you run your program with command line parameters like 12 * 12 you are putting a wildcard in the command line and the shell sees the * and replaces it with a list of every filename in the directory - The first program in the directory must start with a lower case c if the symbol comes out with 99.
To make it work escape your command line parameters like 12 '*' 12 or 12 \* 12 or disable filename globbing altogether as shown in this answer: Stop shell wildcard character expansion?
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
I just want a 1 or 0 if it is prime or not.
but I am getting multiple 0's and 1's. How can I solve this.
#include <stdio.h>
int num() {
int a, i;
printf("Enter a number:");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
printf("1");
else
printf("0");
}
}
int main() {
num();
return 0;
}
Based on the naming used and specific combination of function use, I am almost certain OP's code is based off this which is my first google response to c check if number is prime.
I challenged myself to "fix" it with least number of modification to the original code, here is the version that works the way OP expects. It is ugly but the point is to make it clear where it differs from his code.
OP seems to have mixed up the inner if statements with the outer if statements, and completely forgot about the counter. Also OP seems to have got confused in the function num, as it should either print 1 or 0 and be a void function, or return 1 or 0 and take a as input to a function that returns int eg int num(int a) or void num(), whereas OP ended up going halfway int num().
The working(if you can call it that, since fflush(stdout) is not called after printf is called, so the program will not not show the question on mingw without winpty) program would look like this:
#include <stdio.h>
void num() {
// a is the user input number
// c is the count
// i is the iterator
int a, i, c = 0;
printf("Enter a number: ");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
++c;
}
if (c != 0)
printf("0");
else
printf("1");
}
int main() {
num();
return 0;
}
The reason you get multiple 0s and 1s is you print them for every potential factor. You should instead test the factors to determine if none of the factors up to the square root of the number divide the number evenly, printing a 1 in this case and a 0 otherwise.
Function isprime should take an int argument and return 1 or 0, the main() function takes case of getting the number from the user and printing the result.
Here is a modified version:
#include <stdio.h>
int isprime(int a) {
int i;
if (a < 2)
return 0;
for (i = 2; a / i >= i; i++) {
if (a % i == 0)
return 0;
}
return 1;
}
int main() {
int a;
printf("Enter a number:");
if (scanf("%d", &a) == 1) {
printf("%d\n", isprime(a));
}
return 0;
}
Also note how the code is indented and uses spaces to improve readability. Learn how to do this for your next projects.
I apologize if the title is misleading in anyway, because I don't know where or how to start on this one.
Recently I wrote a math game that makes random numbers and turns them into equations. But all the program can do Is take in numbers, if I wanted to allow commands like say show-stats to show your stats. I have to write the command and then a number after for the command to get recognized like so
show-stats 0
score is 1
show-stats
0 //number is required for some reason
score is 1
This is a minimal example I wrote
#include <stdio.h>
#include <string.h>
int main() {
int bar;
char foo[]="";
int score = 1;
scanf("%s%i",foo,&bar);
if(strcmp(foo,"show-stats"))
{
printf("Score is %i",score);
}
if(bar == 2)
{
score = bar*2;
printf("Doubled Points.\n");
}
}
Here is the actual code, In case you need. Also, I'd like advisors on the actual code, like if its spaghetti or if something is performance consuming, or just what I can improve on in general if its not too much trouble. thanks in advance and I'm open to suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define VER 10
#define DIV "-----"
int main()
{
system("clear");
unsigned int x,y; //equation numbers
int ans,sum; //user answer
unsigned int max = 10; //max possible number that can be made, cannot go under 10.
int score; //what do you think?
char operation;
int correctAnswers = 0,wrongAnswers = 0;
printf("Math game\nVersion %i.\n",VER);
for (; ;)
{
//phase 1; make numbers.
srand(time(NULL));
x = rand() % max;
y = rand() % max;
//phase 2; make operation type.
operation = rand() % 2;
switch (operation)
{
case 0:operation = '+';sum = x + y;break;
case 1:operation = '-';sum = x - y;break;
}
//phase 3; write question to console and get user answer
printf("What is %i %c %i? ",x,operation,y); //get input
scanf("%i",&ans);
//phase 4; determine right answer
if (ans == sum)
{
score++;
correctAnswers++;
max++;
printf("Your correct! +1!\n");
printf("%sStats%s\nScore:%i\nMax possible number:%i\nCorrect Answers:%i\nWrong Answers:%i\n%s%s%s\n",DIV,DIV,score,max,correctAnswers,wrongAnswers,DIV,DIV,DIV); //print stats when user wins,is a seperate call for readability. same thing on line 53 but for loss
}
else
{
score--;
wrongAnswers++;
if(max>10){max--;}; //assures max doesn't go under 10
printf("Wrong! -1\n");
printf("%sStats%s\nThe correct answer was %i\nMax possible number : %i\nScore : %i\nCorrect Answers : %i\nWrong Answers : %i\n%s%s%s\n",DIV,DIV,sum,max,score,correctAnswers,wrongAnswers,DIV,DIV,DIV);
}
}
}
Thanks to DevSolar, I know how to do this. Using fgets() and strtol() you can collect the entire string, and parse it into the command and the number, I read up on strtol here https://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
edit:
char str[30] = ""; //the string the user types
fgets(str,30,stdin);
char *ptr; //the part of the string turned into words
long ret; //the part of the string turned into numbers
ret = strtol(str, &ptr, 10); //parameter 1;source string that is parsed;//parameter 2; string part of source.//parameter 3; base
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
here is the code I wrote.
#include <stdio.h>
#include <stdlib.h>
typedef struct note {
int pitch;
int velocity;
int channel;
} note;
int printnote(int pitch, int velocity, int channel);
int main() {
int size = 100;
note note;
struct note *ptr = malloc(size * sizeof(int));
printf("Input the values for the `pitch`, `velocity`, and `channel`\n");
scanf("%d %d %d", ¬e.pitch, ¬e.velocity, ¬e.channel);
printnote(note.pitch, note.velocity, note.channel);
free(ptr);
return 0;
}
int printnote(pitch, velocity, channel) {
printf("The MIDI Note is:\n");
printf("Pitch -> %d\n", pitch);
printf("velocity -> %d\n", velocity);
printf("channel -> %d\n", channel);
return 0;
};
When I run the code and type the numbers, it shows the wrong answers.
For example, I run the code, and it shows
Input the values for the `pitch`, `velocity`, and `channel`
5 5 5
The MIDI Note is:
Pitch -> 5
velocity -> 0
channel -> -429762432
The three numbers should be the same as the input numbers.
Can anyone help me?
There is a subtle typo in your scanf() conversion string:
scanf("%d %d %d", ¬e.pitch, ¬e.velocity, ¬e.channel);
You used the unicode full width percent sign % (\uff05) instead of the ASCII % character. scanf does not recognise this as a conversion specifier and tries to match the byte sequence used to encode %, (0xEF 0xBC 0x85 in UTF-8) and fails thus only converting the first input into note.pitch and leaving note.velocity and note.channel uninitialized, returning 1. Note how % looks different from % in the fixed font used for code, but identical in the font used for this text: % % % % % %.
Just replace % with the correct character:
scanf("%d %d %d", ¬e.pitch, ¬e.velocity, ¬e.channel);
Also note these remarks:
size and ptr are not used in main(),
you should check the return value of scanf() to detect invalid input. This check would have helped find the error,
the prototype in the definition of printnote is incorrect: the argument types are missing,
the ; after the } is useless,
using the same identifier note for the variable and its type is confusing.
Here is modified version:
#include <stdio.h>
typedef struct note {
int pitch;
int velocity;
int channel;
} note;
void printnote(int pitch, int velocity, int channel);
int main() {
note note1;
printf("Input the values for the `pitch`, `velocity`, and `channel`\n");
if (scanf("%d %d %d", ¬e1.pitch, ¬e1.velocity, ¬e1.channel) != 3) {
printf("invalid input\n");
return 1;
}
printnote(note1.pitch, note1.velocity, note1.channel);
return 0;
}
void printnote(int pitch, int velocity, int channel) {
printf("The MIDI Note is:\n");
printf("pitch -> %d\n", pitch);
printf("velocity -> %d\n", velocity);
printf("channel -> %d\n", channel);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The following is an attempt to print a number of fibonacci sequence numbers, determined by the user. Uses a user-define function, fibonacci(int a). It is printing the wrong output, not a recursive sequence, but a continually doubling sequence. How can the code be fixed so that it works correctly?
#include <stdio.h>
int fibonacci(int a);
void main()
{
int number, range;
printf("Enter the number of Fibonacci numbers: ");
scanf("%d", &range);
number = fibonacci(range);
printf("%d\n", number);
}
int fibonacci(int a)
{
int num1 = 1;
int num2 = 1;
int position;
if (a == 1)
{
printf("%d", num1);
}
if (a == 2)
{
printf("%d\n", num1);
printf("%d", num2);
}
if (a > 2)
{
for(position = 1; a >= position; position++)
{
printf("%d\n", num1);
num1 = num2;
num2 = num1 + num2;
}
}
}
This prints the following output for all numbers:
1
1
2
4
8
16
...
The desired output is the fibonnaci sequence (each number is the sum of the two previous ones):
1
1
2
3
5
8
13
...
The problem is that within the loop you first overwrite num1 by assigning num2 to it:
num1 = num2;
Then you make num2 be the sum of itself and num1, but you have just made num1 equal to num2, so this line is effectively just multiplying num2 by two (i.e., adding it to itself):
num2 = num1 + num2;
You need to preserve the old value and use that for the sum, e.g., by adding a third, temporary, variable.
(Apart from this, you also have various other problems, but all of them are such that they should produce compiler warnings. If they don't, enable all warnings and/or get a better compiler. Once you get warnings, don't ignore them but research the cause for each of them and fix all warnings before you even run your code.)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to check if the numbers in an array are a power of two.
I wrote the following code, but it doesn't work it skips the part that checks if the number is the power of two and prints the last sentence.
Also, if someone can help me in how to check if the input is a number and not any other character.
Thank you!
update the power of two thing is working but i still haven't figure out how to check if the input is a number and not any other characher
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
int i;
int k;
int count=0;
int a;
int sum=0;
printf("Enter size of input:\n");
scanf("%d",&x);
int *numbers=malloc(sizeof(int)*x);
if (x<0){
printf("Invalid size\n");
}
else {
printf("Enter numbers:\n");
for(i=0;i<x;++i){
scanf("%d",&numbers[i]);
}
}
for(k=0;k<x;++k)
{
count=0;
a=numbers[k];
while (((numbers[k] % 2) == 0) && numbers[k] > 1){ /* While x is even and > 1 */
numbers[k]/= 2;
++count;
}
if (numbers[k]==1&&a!=1){
printf("The number %d is a power of 2:%d=2^%d\n",a,a,count);
sum+=count;
}
}
printf("Total exponent num is %d\n",sum);
return 0;
}
Your check for the power of two is wrong: you divide out two all the way down to 1, but the following if incorrectly checks numbers[k]==0.
The check should be numbers[k]==1 instead, because when you divide out all twos from a power of two you end up with 20, which is 1.
Note: You can check if a number is a power of two without a loop by using a bit trick described in this Q&A.
There's much in your example that's incidental to the problem. For example, allocating an array and reading user input is just a distraction from finding the solution. Concentrate first on debugging your algorithm:
#include <stdbool.h>
bool is_power_of_two(int n)
{
while (n % 2 == 0 && n > 1){ /* While x is even and > 1 */
n/= 2;
}
return n == 0;
}
int main()
{
return !is_power_of_two(2);
}
Now, you can refine that function until it gives the correct result. The simple fix is to replace n == 0 with n == 1. Now you can add more tests, running the program as you add each one:
int main()
{
return is_power_of_two(0)
+ !is_power_of_two(1)
+ !is_power_of_two(2)
+ is_power_of_two(3)
+ !is_power_of_two(4)
/* negative numbers can never be an exact power of a positive */
+ is_power_of_two(-1)
+ is_power_of_two(-2)
+ is_power_of_two(-3);
}
Once you have some confidence in your function, you can then use it in your program to process arrays.
When you do introduce a function to read input, you'll want to check that x isn't negative before using in the argument to malloc(). Better would be to ensure it's not negative, by using an unsigned type:
unsigned int x;
printf("Enter size of input:\n");
if (scanf("%u", &x) != 1) {
fprintf(stderr, "That's not a valid size!\n");
return EXIT_FAILURE;
}
int *numbers = malloc(x * sizeof *numbers);
if (!numbers) {
fprintf(stderr, "Couldn't allocate memory for %u numbers!\n", x);
return EXIT_FAILURE;
}