I have this code below which is suppose to generate the output of 11 dwarfs for input of 10 for dwarf height and values of 101, 102, 103, 104,105, 106, 107, 108, 109 as well as 110 for giant height then change to output of 12 dwarfs for values of giant height of 111-120 and so forth when the height of dwarf again is 10. Both 'n' and 's' have essentially the same solution: proper output of dwarfs for values of 101 - 109 but not correct output (should be 11, but gives 10) for the value of 110. What operators can be used to help with this. I am working on my operator usage and would strongly prefer not to use any conditional statements or if-then.
#include <stdio.h>
int main()
{
int g, d, n, s;
while(1)
{
printf("enter the heights of giant and drwafs: ");
scanf("%d%d", &g, &d);
n = g % d + (g/d) + (-g % d + 1) - (g%d + 1)/10;
s = g / d + 1;
printf("%d",s);
printf("it takes %d dwarfs to be "
"greater than or equal to giant.\n\n", s );
}
return 0;
}
Ceiling of integer division:
unsigned int dividend, divisor, c;
/* dividend != 0 && divisor != 0 */
c = 1 + ((dividend - 1) / divisor);
Your program would then look something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned int giant, dwarf, c;
printf("Height of giant: ");
scanf("%u", &giant);
printf("Height of dwarf: ");
scanf("%u", &dwarf);
/* the heights can't be 0 */
if (giant == 0 || dwarf == 0) {
printf("The heights need to be greater than 0.\n");
exit(EXIT_FAILURE);
}
/* ceil giant divided by dwarf */
c = 1 + ((giant - 1) / dwarf);
printf("It takes %u dwarfs to be as high "
"or higher than a giant.\n", c);
return 0;
}
You can use the NOT operator, if you have a remainder it will add 1, if you have no remainder it will just be the result of your division:
include <stdio.h>
int main()
{
int g, d, s;
while(1)
{
printf("enter the heights of giant and drwafs: ");
scanf("%d %d", &g, &d);
if (d <= 0 || g <= 0) // what if your user use 0 for the size of dwarf? ouch...
continue
s = g / d + !!(g % d);
printf("%d",s);
printf("it takes %d dwarfs to be "
"greater than or equal to giant.\n\n", s );
}
return 0;
}
NB: This solution works with giant = INT_MAX
Related
My code:
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
printf("%d %s ", (int)pow(10, power) - 1, power == n ? "=" : "+");
sum += (int)pow(10, power) - 1;
}
printf ("%d", sum);
return 0;
}
Output in Vs Code with gcc:
Enter a number: 5
9 + 98 + 999 + 9998 + 99999 = 111103
Output in online compilers:
Enter a number: 5
9 + 99 + 999 + 9999 + 99999 = 111105
My question: Why? is this happening?
Possibly an issue with pow and its implementation, perhaps due to different platform or compilers.
Instead of using pow which relies on floating point arithmetic and leads to compounding rounding errors (and possibly contains bugs), why not use simple multiplication? If you start the loop with 10, then you could multiply that by 10 each iteration to get the result you want.
Perhaps something like this:
unsigned sum = 0;
for (unsigned power = 0, value = 10; power < n; ++power, value *= 10)
{
sum += value - 1;
}
[Printing left out]
I just use the function "round" which returns the integer rounding closest to the value specified in parameter
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum=0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
sum += (int)round (pow(10, power)) - 1;
}
printf ("%d", sum);
return 0;
}
#include <stdio.h>
main()
{
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
if(i==1) //for 1st
printf("1st value : ");
else if (i<=2) //2nd
printf("2nd value : ");
else if (i<=3) //3rd
printf("3rd value : ");
else //else print th ordinal
printf("%dth value : ", i);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
A program to take out the average of n numbers.
Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance.
There isn't a standard function that does that. You can write one, or use mine:
ordinal.c
#include "ordinal.h"
#include <stdio.h>
static const char *const suffixes[4] = { "th", "st", "nd", "rd" };
enum { NUM_SUFFIXES = sizeof(suffixes) / sizeof(suffixes[0]) };
static unsigned suffix_index(unsigned n)
{
unsigned x;
x = n % 100;
if (x == 11 || x == 12 || x == 13)
x = 0;
else if ((x = x % 10) > 3)
x = 0;
return x;
}
char *fmt_ordinal(char *buffer, size_t buflen, unsigned n)
{
unsigned x = suffix_index(n);
int len = snprintf(buffer, buflen, "%u%s", n, suffixes[x]);
if (len <= 0 || (size_t)len >= buflen)
return 0;
return(buffer);
}
ordinal.h
/* returns buffer or 0 on failure (implausible unless buffer too small) */
extern char *fmt_ordinal(char *buffer, size_t buflen, unsigned n);
Some of that is overkill on its own, but the source file also contains scn_ordinal() which scans ordinal numbers with greater or lesser strictness, and the header declares it.
int main(void)
{
char buffer[15];
/* Test fmt_ordinal() */
for (unsigned i = 0; i < 35; i++)
printf("%2u => %4s\n", i, fmt_ordinal(buffer, sizeof(buffer), i));
return 0;
}
You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.
if ((i % 10 == 1) && (i % 100 != 11))
printf("%dst value : ", i);
else if ((i % 10 == 2) && (i % 100 != 12))
printf("%dnd value : ", i);
else if ((i % 10 == 3) && (i % 100 != 13))
printf("%drd value : ", i);
else
printf("%dth value : ", i);
I played with this a bit and this was my minimal 'lookup' except, sadly, for the expense of the modulo division. I wasn't fussed about values above 99.
if( i > 20 ) i %= 10; // Change 21-99 to 1-10.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.
You can use 'suffix' as a pointer to a normal null terminated string.
It is okay to be a beginner, no need to apologize. You can solve your problem using a combination of a SWITCH statement and the modulus operator (%). The modulus operator takes two numbers (n1 % n2) and returns the remainder when n1 is divided by n2.
You will want to construct an array of ordinals, like this:
char *ordinalList[] = { "st", "nd", "rd", "th" };
This will allow you to simply reference this array to append the correct ordinal to a number. The next step is to create an algorithm to determine which array index should be referenced. To do this, you can make a new function and call it in your "main".
char *determineOrdinal (char **ordinalList, int numValue)
{
if (3 < numValue && numValue < 21)
return ordinals[3];
switch (numValue % 10) {
case 1 : return ordinalList[0];
break;
case 2 : return ordinalList[1];
break;
case 3 : return ordinalList[2];
break;
default: return ordinalList[3];
break;
}
You can pass a number into this function as the numValue argument. Your "main" function might look something like this:
#include <stdio.h>
int main(void)
{
char *ordinalList[] = { "st", "nd", "rd", "th" };
char *currentdOrdinal;
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
currentdOrdinal = determineOrdinal (ordinalList, i)
printf("%d%s value : ", i, currentdOrdinal);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
I think that code should work for you. I hope this helps.
//Enter a 4-digit integer n from the keyboard, and write a program to divide it into two 2-digit integers a and B. Calculate and output the results of the addition, subtraction, multiplication, division and redundancy operations of the split two numbers. For example, n=-4321, if the two integers after splitting are a and b, then a=-43 and b=-21. The result of division operation requires that it be precise to 2 decimal places, and the data type is float. Redundancy and division operations need to take into account the division of 0, that is, if the split B = 0, then output the prompt information "The second operator is zero!"
//Failure to pass the test,how should i fix
#include<stdio.h>
#include<math.h>
int main()
{
int x, a, b;
printf("Please input n:\n");
scanf("%d", &x);
a = x / 100;
b = x % 100;
printf("%d,%d\n", a, b);
printf("sum=%d,sub=%d,multi=%d\n", a + b, a - b, a*b);
if (b == 0)
printf("The second operater is zero!");
else
printf("dev=%.2f,mod=%d\n", (float)a / b, a%b);
}
You forgot to check that x is a 4-digits number. So if the input is 12345 or 123 you don't satisfy the requirement.
#include <stdio.h>
int main()
{
int x, a, b;
int passed = 0;
// Enter a 4 digits number: ABCD
do {
printf("Enter X = ");
scanf("%d", &x);
passed = (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000);
} while (!passed);
a = x / 100;
b = x % 100;
printf("Numbers: %d %d \n", a, b);
printf("Sum = %d \n", a + b);
printf("Sub = %d \n", a - b);
printf("Mul = %d \n", a * b);
if (0 == b) {
printf("Div by Zero \n");
} else {
printf("Div = %f \n", (double)a / b);
printf("Mod = %d \n", a % b);
}
return 0;
}
I have to write a program in C that will take a base b from the user (assuming b is between 2 and 10), a natural number n and then n numbers that represent the digits of some number m in base b. The program should print out what decimal number m was input. For example, if you put b=5 and n=4 and then the numbers 3 ,4, 2 and 1 the program should output 486 because m=3*5^3+4*5^2+2*5^1+1*5^0=486
Note: You can assume that the digits will be the numbers between 0 and b-1.
So here's what I've done:
#include<stdio.h>
#include<math.h>
int main(void) {
int x,n,b,k=0,num=0,i,j;
scanf("%d", &b);
scanf("%d", &n);
for(i=1; i<=n; i++) {
scanf("%d", &x);
for(j=1; j<b; j++){
if(j>k){
num=num+x*(pow(b,n-j));
k=j;
break;
}
}
}
printf("m=%d", num);
return 0;
}
Can you tell me why this doesn't work for the numbers given in the example above? It outputs 485 instead of 486, while if I take for example b=7, n=3 and then numbers 5, 6 and 1, I get the correct solution m=288.
I suggest checking the return value of scanf(), Something like this is the right idea:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int
main(int argc, char *argv[]) {
int base, n, i, x, sum = 0, power;
printf("Enter base: ");
if (scanf("%d", &base) != 1) {
printf("Invalid base.\n");
exit(EXIT_FAILURE);
}
printf("Enter n: ");
if (scanf("%d", &n) != 1) {
printf("Invalid n.\n");
exit(EXIT_FAILURE);
}
power = n-1;
printf("Enter numbers: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &x) != 1) {
printf("Invalid value.\n");
exit(EXIT_FAILURE);
}
sum += x * pow(base, power);
power--;
}
printf("Sum = %d\n", sum);
return 0;
}
Input:
Enter base: 5
Enter n: 4
Enter numbers: 3 4 2 1
Output:
Sum = 486
You need some small change to your logic.
#include <stdio.h>
#include <math.h>
int main(void) {
int x, n, b, num = 0, i;
scanf("%d", &b);
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d", &x);
num += x * pow(b, n - i);
}
printf("m=%d", num);
return 0;
}
Test
gcc -Wall main.c -lm
$ ./a.out
5
4
3
4
2
1
m=486
Test 2
./a.out
7
3
5
6
1
m=288
OK, so given a binary number, we can output a decimal number very easily. Just printf("%d%\n", x);
Next job is to convert a number given digits and base into a binary (machine representation) number.
int basetointeger(const char *digits, int b)
{
assert(b >= 2 && b <= 10);
// code here
return answer;
}
Now hook it all up to main
int main(void)
{
int x;
int base;
char digits[64]; // give more digits than we need, we're not worrying about oveflow yet
/* enter base *?
code here
/* enter digits */
code here
x = basetointger(digits, base);
printf("Number in decimal is %d\n, x);
}
I am trying to learn how to convert ints into binary. it runs but this is the output: Enter a number: 33
New value: 16
Remainder: 1
Current VAlue: -17
Counter: 1
I appreciate any help. Thank you. Ok I am sorry my bad. The output should be: 00100001
#include <stdio.h>
int main()
{
int nv, r, num;
printf("Enter a number: ");
scanf("%d",&num);
int counter=0;
while(num>=0)
{
nv=num/2;
r=num%2;
num=-(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d",num);
}
printf("Counter: %d\n",counter);
}
num=-(nv+r);
Is obviously negative, since both nv and r are positives.
I suspect you actually wanted
num = nv
or:
num -= (nv + r)
Also note that your stop condition is num >= 0 - if you do the first change, you will get an infinite loop, since when you reach num ==0, you will divide by 2, and get nv == num /2 == 0 / 2 == 0 and assign nv back to num
(*)Note that also the second change will proide infinite loop: 0 % 2 == 0 and 0 / 2 == 0, so num -= (nv + r) == 0 - (0 + 0) == 0
Is this what you were trying to accomplish?
#include <stdio.h>
int main()
{
int nv, r, num;
int counter=0;
printf("Enter a number: ");
scanf("%d",&num);
while(num>0)
{
nv=num/2;
r=num%2;
num-=(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d\n",num);
}
printf("Counter: %d\n",counter);
return 0;
}
One easy way to do that is know that the machine store the number in binary. And what you need to do is only use this to print the number in binary.
int main()
{
int val=1;
int n=0;
int num;
printf("Enter a number: ");
scanf("%d",&num);
while(val <= num)
{
if(val & num) printf("bit %d is '1'\n", n);
else printf("bit %d is '0'\n", n);
n++;
val<<=1;
}
}
In this case the order is from the least significant to the most significant bit.