Why did I get different answers in vscode? - c

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;
}

Related

Write a C program that accepts two numbers and finds all Armstrong numbers in that range

In the above mentioned I wanted to ask that what I have done wrong in my code I have tried debugging it many times but was not able to understand the logical error in my code.
Any help would be appreciated.
#include <stdio.h>
#include <math.h>
int digit(int n);
int digit(int n) {
int a;
double i = 0;
do {
a = n % (int)(pow(10, i));
i++;
} while (a != n);
return i;
}
void is_armstrong(int n);
void is_armstrong(int n) {
int a, b;
double sum;
for (int i = 0; i < digit(n); i++) {
a = n / (int)pow(10, (double)i);
b = a % 10;
sum += pow((double)b, 3);
}
if ((int)sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
is_armstrong(153);
return 0;
}
This code is not even showing 153 an Armstrong number.
Noting the comments about using the power function and what your ultimate outcome is in identifying Armstrong numbers over a given range, I did a bit of refactoring to simplify the process in identifying such numbers. Following is the code snippet that provides the functionality.
#include <stdio.h>
void is_armstrong(int n) {
int a, b, c, d;
int sum = 0;
a = n;
c = 0;
while (a != 0) /* Determine the number of digits to raise to a power */
{
a = a / 10;
c = c + 1;
}
a = n; /* Reset the work number */
while (a != 0) /* Noted from the comments to simplify the test */
{
b = a % 10;
d = b;
for (int i = 1; i < c; i++)
{
d = d * b;
}
sum = sum + d; /* Just mulitply each digit by itself the required number of times */
a = a / 10; /* Divide by 10 along with using the modulo function to evaluate each digit */
}
if (sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
return 0;
}
Following are some key points.
Since the power function is not needed, the math.h include file is not needed and linking the math library is also not needed.
Acquiring each digit is simplified by just utilizing the modulo operation in combination with integer division by "10".
Acquiring the value of each digit raised to the nth power is simplified by just performing a repeated multiplication.
Following is test output at the terminal.
#Dev:~/C_Programs/Console/Armstrong/bin/Release$ ./Armstrong
Please input the left hand limit of range :
1
Please input the right hand limit of range :
10000
1 is an armstrong number.
2 is an armstrong number.
3 is an armstrong number.
4 is an armstrong number.
5 is an armstrong number.
6 is an armstrong number.
7 is an armstrong number.
8 is an armstrong number.
9 is an armstrong number.
153 is an armstrong number.
370 is an armstrong number.
371 is an armstrong number.
407 is an armstrong number.
1634 is an armstrong number.
8208 is an armstrong number.
9474 is an armstrong number.
And as a confirmation, it can be seen that the value "153" was recognized as an Armstrong number.
Give the code snippet a try and see if it meets the spirit of your project.
There is no need to count the number of digits in n, you can just sum the cubes of each digit, one at a time dividing the number by 10 at each iteration.
Here is a simplified version:
#include <stdio.h>
void is_armstrong(int n) {
int sum = n;
while (n != 0) {
int b = n % 10;
n /= 10;
sum -= b * b * b;
}
return sum == 0;
}
int main() {
int a, b;
printf("Please input the left hand limit of range:\n");
if (scanf("%d", &a) != 1)
return 1;
printf("Please input the right hand limit of range:\n");
if (scanf("%d", &b) != 1)
return 1;
for (int i = a; i <= b; i++) {
if (is_armstrong(i)) {
printf("%d is an Armstrong number.\n", i);
}
}
return 0;
}

input and Output with math in C

Example
Input: 12345
Output: (1+2+3+4+5=15)--> (1+5=6) Output is 6
(It shoud be only one number (1-9)
Please tell me how to make sure that when you enter a number, for example 12345, the output is equal to the sum 1 + 2 + 3 + 4 + 5 = 15 and then 1 + 5 = 6. C language. Thank you very much for your answer!
#include <stdio.h>
int main(){
int isicc;
scanf ("%d", &isicc);
while (isicc>0){
int d = isicc%10;
isicc=isicc /10;
}
printf ("Your number ", d);
}
After the command
scanf ("%d", &isicc);
You can use this code to get the sum of digits of the number:
int sum_digits = 0;
while (isicc > 0) {
sum_digits += isicc % 10;
isicc = isicc / 10;
}
isicc = sum_digits;
Now, you just need to repeat this process in another loop , that will continue as long as isicc is bigger than 9.
#include <stlib.h>
#include <stdio.h>
int main(){
int isicc;
scanf ("%d", &isicc);
isicc = abs(isicc);
printf ("Your number %d\n", isicc?isicc%9?isicc%9:9:0 );
}
Try this program, it will add digits and print sum
#include <stdio.h>
int main ()
{
int num,n,sum=0;
printf ("Enter number:");
scanf (" %d",&num);
while (num!=0){
n=num%10;
sum += n;
num = num/10;
}
printf ("%d",sum);
return 0;
}

How do I print ordinal indicators in a C program? Can't print numbers with 'st', 'nd', 'rd'. (Beginner)

#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.

Calculating the average of user inputs in c

disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.

Write a program in C that will take a base and n digits and will output a decimal number represented by those digits

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);
}

Resources