C# - What's wrong with my conversion from double to int? - c#

I keep getting this error:
"Cannot implicitly convert type 'double' to 'int'. An explicit
conversion exists (are you missing a cast?)"
Code:
Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
int ISBN = Convert.ToInt32(ISBNstring);
int PZ;
int i;
double x = Math.Pow(3, (i + 1) % 2);
int y = (int)x;
for (i = 1; i <= 12; i++)
{
PZ = ((10-(PZ + ISBN * x) % 10) % 10);
}
Console.WriteLine(PZ);
Console.ReadLine();
Here is the new code:
Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
long ISBN = Convert.ToInt32(ISBNstring);
long ISBN1 = (Int64)ISBN;
int PZ = 0;
int i;
for (i = 1; i <= 12; i++)
{
double x = Math.Pow(3, (i + 1) % 2);
long y = (double)x;
PZ = ((10 - (PZ + ISBN * y) % 10) % 10);
}
Console.WriteLine(PZ);
Console.ReadLine();
But I'm still getting a conversion error for double to long and long to int...

I think you meant to use your y variable here instead of x :
PZ = ((10-(PZ + ISBN * y) % 10) % 10);
As a side note, you'll get compilation errors on both PZ and i, you need to initialize their values before using them, e.g. int PZ = 0; and int i = 0;
And please, use meaningful names; PZ, i, x and y don't mean anything to someone reading your code, or even to you in a few weeks.
Okay, I've modified it a little...
Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
int sum = 0;
for (int i = 0; i < 12; i++)
{
int digit = ISBNstring[i] - '0';
if (i % 2 == 1)
{
digit *= 3;
}
sum += digit;
}
int result = 10 - (sum%10);
Console.WriteLine(result);
Console.ReadLine();
Here's the changes :
- You can declare i directly in your for loop, it'll save you a line.
- Instead of putting the ISBN into a long, keep in in a string. Just iterate over each character one by one.
- Each digit can be obtained by taking the ASCII value, and removing the value of 0.
- The % 2 == 1 thing is basically "If the number is at an odd position", where you can apply the *3. This replaces your Math.Pow that wasn't very clear.

Related

Float Evaluation returns integer?

I recently started with the euler Project for practice, I completed 1 and 2, but 3 is just not working. I used the same line of code for every solution to check if the number is decimal or not. This worked fine except this time, but I dont know why. This code
for (float i = 0; i < 1000; i++)
{
float temp = i / 3;
float temp2 = i/ 5;
if ((temp % 1) == 0 || (temp2 % 1) == 0)
{
num += i;
}
}
worked perfectly fine, but this one (which is basically the same)
float input = 600851475143;
for (float i = 0; i < 1000; i++)
{
float temp = input/i;
if ((temp % 1) == 0)
{
Console.Write(temp + ", ");
}
just returns every number. Then I tried this
float temp = 10/9;
Console.WriteLine(temp);
But it just returns 1. So i thought of an overflow or something like that, but my next approach didnt work either:
float temp = 10/9;
bool temp2 = (temp%1) == 0;
Console.WriteLine(temp2);
Return: True
I dont now what to do anymore, does someone know why this happens? Thanks in advance.
float in C# has precision of 6-9 digits according to docs, 600851475143 divided by maximum i in the loop (i.e. 999) will have more than 9 digits in mantissa so float will not be able to cover fractional part, so try switching to double or even decimal:
double input = 600851475143;
for (double i = 0; i < 1000; i++)
{
double temp = input / i;
if ((temp % 1) == 0)
{
Console.Write(temp + ", ");
}
}
Also I would say that you can use long's in this case:
long input = 600851475143;
for (long i = 1; i < 1000; i++)
{
var x = (input % i);
if (x == 0)
{
Console.WriteLine(input / i);
}
}
As for the last snippet - 10 and 9 in 10/9 are int's, so the result of 10/9 is an int and equals to 1, which give you the result you get.

How to take the sum of only even and odd numbers? C#

When the user enters numbers, say 3 and 7, the program adds all of the number in between and the numbers the user entered. Now I need to make it add only the even and odds in between the numbers. This is what I have so far:
static void Exercise1()
{
int min;
int max;
int sum = 0;
int odd = 0;
int even = 0;
Console.WriteLine("Enter minimum integer: ");
min = int.Parse(Console.ReadLine());
Console.WriteLine("Enter maximum integer: ");
max = int.Parse(Console.ReadLine());
//Sum of all
Console.Write("All: ");
for (int x = min; x <= max; x++)
{
Console.Write(min);
min++;
Console.Write(" + ");
sum += x;
}
Console.Write("= ");
Console.Write(sum + "\n");
//Odd Numbers
Console.Write("Odd: ");
for (int x = min; x <= max; x++)
{
if (min % 2 != 0)
{
Console.Write(min);
min++;
Console.Write(" + ");
odd += x;
}
}
Console.Write("= ");
Console.Write(odd + "\n");
//Even Numbers
Console.Write("Even: ");
for (int x = min; x <= max; x++)
{
if (min % 2 == 0)
{
Console.Write(min);
min++;
Console.Write(" + ");
even += x;
}
}
Console.Write("= ");
Console.Write(even + "\n");
}
I can find the sum of all the numbers but what I have tried here is the extent of my knowledge. I have hit a dead end.
You're doing min++ within the loops, which means min is not what it should be. It is sometimes a reasonable micro-optimisation to do ++min and not have an x at all, but only if you're never going to need that value again.
You could speed things up by skipping x += 2 in each loop once you've found the odd (or even, accordingly), but speed things even more so by having one loop:
int sum = 0;
int odd = 0;
int even = 0;
for (int x = min; x <= max; x++)
{
sum += x;
if (x % 2 == 0)
even += x;
else
odd += x;
}
However you can do much better with a bit of mathematical thinking on it.
∑[x, y] = (y - x + 1)(y + x)/2
E.g. from 5 to 9 is 5 + 6 + 7 + 8 + 9 = 35 and also is (9 - 5 + 1) * (5 + 9) / 2 = 35.
So to find the sum you don't need a loop, you need:
int sum = (max - min + 1) * (max + min) / 2;
This would make a big difference in speed if min was -1024 and max was 8980 because you can just do this calculation and get 39799890 rather than having to loop through 10005 different values.
Similarly if you find the min even number (minEven = min % 2 == 0 ? min : min + 1) and the max even number (maxEven = max % 2 == 0 ? max : max - 1) then you can find the sum of evens with:
int sumEven = ((maxEven - minEven) / 2 + 1) * (maxEven + minEven) / 2;
And indeed the exact same formula works for odd:
int sumOdd = ((maxOdd - minOdd) / 2 + 1) * (maxOdd + minOdd) / 2;
There, there's no need to do any looping at all, and your Θ(n) approach can be replaced with a Θ(1) approach.
The problem is that you are confusing the roles of x and min. min is entered by the user and serves as the starting point for your method; you shouldn't be changing it. However, you change min during each iteration of your for loops. So first of all, remove min++ from all three of your for loops.
x is a variable that changes as your find the sums. So instead of Writing the value of min to console (this value should be constant, you are really trying to find out what the value of x is... So, change your Console.Write(min) to Console.Write(x)
Also change your if-statement from
if (min % 2 != 0)
to
if (x % 2 != 0)
You can brush up on the for-loop (and other) control statements by reading this lesson or watching this video.
Here's a way worth looking at:
static void Exercise1()
{
Console.WriteLine("Enter minimum integer: ");
int min = int.Parse(Console.ReadLine());
Console.WriteLine("Enter maximum integer: ");
int max = int.Parse(Console.ReadLine());
IEnumerable<int> all = Enumerable.Range(min, max - min + 1);
IEnumerable<int> odds = all.Where(n => n % 2 == 1);
IEnumerable<int> evens = all.Where(n => n % 2 == 0);
Console.WriteLine(String.Format("All: {0} = {1}", String.Join(" + ", all), all.Sum()));
Console.WriteLine(String.Format("Odd: {0} = {1}", String.Join(" + ", odds), odds.Sum()));
Console.WriteLine(String.Format("Even: {0} = {1}", String.Join(" + ", evens), evens.Sum()));
}
That should give you something to thing about.

Compute for the summation of X^2

Given x = 3;
I need to compute for the summation of the value of x = 3 + 2 + 1
x = 6;
int input = 3;
int retVal = 0;
for (int i = 0; i <= input; i++)
{
retVal += i;
}
Console.WriteLine(retVal);
I was able to compute for the summation of x.
How can i compute for the value of summation of x^2
for example
x x^2
1 1
2 4
3 9
summation of x = 6
summation of x^2 = 14
I have tried the following code
int input = 3;
int retVal = 0;
int summation = input * input;
for (int i = 0; i <= input; i++)
{
retVal += i;
summation += i;
}
Console.WriteLine(retVal);
Console.WriteLine(summation);
Let me explain you your code:
int input = 3;
int retVal = 0;
int summation = input * input; //summation is equal to 9
for (int i = 0; i <= input; i++)
{
retVal += i;
summation += i; /*this is basically saying add summation plus i
tosummation (9 is assigned 9 + 0 so summation is still 9). Then, when i is 1,
summation changes to 10. When i is 2, summation changes to 12, and when i is 3,
summation is 15. What you should be doing is initialize summation to 0 and in
the for loop, do this: summation += i * i (summation is assigned summation + (i * i)) Also, no need to start i from 0 (it is doing one extra loop for nothing). You should start i from 1. */
}
Console.WriteLine(retVal);
Console.WriteLine(summation); //Another user already provided the solution. I just wanted to explain you your code.
int input = 3;
int retVal = 0;
int summation = 0; //<=Chnaged from input * input
for (int i = 1; i <= input; i++) //<=Changed from 0 to 1
{
retVal += i;
summation += i * i; //<= changed from i
}
Console.WriteLine(retVal);
Console.WriteLine(summation);
You need to take power of value before adding by using Math.Pow
var input = 3;
var summation = 0;
var power = 2;
for (int i = 1; i <= input; i++) //initialize i = 1 because first entry is 1 don't start it from 0
{
summation += (int)Math.Pow(i, power);
}
Console.WriteLine(summation);
You can use Enumerable.Range() to achieve this.
public static int Summation(int count, Func<int, int> series)
{
return Enumerable.Range(1, count).Select(series).Sum();
}
Example of use - Summation(3, x => x * x) would return 14.

Digit sum in for loop C#

I wrote I method which is suppose to recieve a nubmer from user and then check number from 0 to 1000. Then it should return all number which have digit sum equal to recieved number. So if I enter 6, it should return numbers like 6, 42, 51, 33, 123 etc. I'd really appreciate help since I've been dwelling on this for a while now.
public static double number() {
Console.WriteLine("Enter your number! ");
string enter = Console.ReadLine();
double x = Convert.ToDouble(enter);
for (int i = 0; i < 1000; i++ ) {
double r;
double sum = 0;
while (i != 0) {
r = i % 10;
i = i / 10;
sum = sum + r;
}
if (sum == x) {
Console.WriteLine(i + " ");
}
}
return(0);
}
I am aware of the fact that there is a problem with "return(0)", but I'm not completely sure what exactly it is that this should be returning.
I'd suggest trying to do something like this:
public static IEnumerable<int> number()
{
Console.WriteLine("Enter your number!");
string enter = Console.ReadLine();
int digitSum = int.Parse(enter);
foreach (var n in Enumerable.Range(0, 1000))
{
if (n.ToString().ToCharArray().Sum(c => c - '0') == digitSum)
{
yield return n;
}
}
}
When I run this and enter 6 then I get this result:
You are almost there: the only remaining problem is that you are modifying your loop counter i inside the nested while loop, which changes the workings of the outer loop.
You can fix this problem by saving a copy of i in another variable, say, in ii, and modifying it inside the while loop instead:
double r;
double sum = 0;
int ii = i;
while (ii != 0) {
r = iCopy % 10;
ii /= 10;
sum = sum + r;
}

Sum of digits in C#

What's the fastest and easiest to read implementation of calculating the sum of digits?
I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21
You could do it arithmetically, without using a string:
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
I use
int result = 17463.ToString().Sum(c => c - '0');
It uses only 1 line of code.
For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.
n = Math.Abs(n);
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.
public static int SumDigits(int value)
{
int sum = 0;
while (value != 0)
{
int rem;
value = Math.DivRem(value, 10, out rem);
sum += rem;
}
return sum;
}
int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
I like the chaowman's response, but would do one change
int result = 17463.ToString().Sum(c => Convert.ToInt32(c));
I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)
I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.
I thought I'd just post this for completion's sake:
If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be
int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;
int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();
I would suggest that the easiest to read implementation would be something like:
public int sum(int number)
{
int ret = 0;
foreach (char c in Math.Abs(number).ToString())
ret += c - '0';
return ret;
}
This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.
I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.
private static int getDigitSum(int ds)
{
int dssum = 0;
while (ds > 0)
{
dssum += ds % 10;
ds /= 10;
if (dssum > 9)
{
dssum -= 9;
}
}
return dssum;
}
This is to provide the sum of digits between 0-9
public static int SumDigits1(int n)
{
int sum = 0;
int rem;
while (n != 0)
{
n = Math.DivRem(n, 10, out rem);
sum += rem;
}
return sum;
}
public static int SumDigits2(int n)
{
int sum = 0;
int rem;
for (sum = 0; n != 0; sum += rem)
n = Math.DivRem(n, 10, out rem);
return sum;
}
public static int SumDigits3(int n)
{
int sum = 0;
while (n != 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
Complete code in: https://dotnetfiddle.net/lwKHyA
int j, k = 1234;
for(j=0;j+=k%10,k/=10;);
A while back, I had to find the digit sum of something. I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, i.e. when the digit sum was 4, i'd get 4.44444444444444 etc.
Hence I edited it, getting the digit sum correct each time with this code:
double a, n, sumD;
for (n = a; n > 0; sumD += n % 10, n /= 10);
int sumI = (int)Math.Floor(sumD);
where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.
static int SumOfDigits(int num)
{
string stringNum = num.ToString();
int sum = 0;
for (int i = 0; i < stringNum.Length; i++)
{
sum+= int.Parse(Convert.ToString(stringNum[i]));
}
return sum;
}
If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Please Input number");
Console.WriteLine(GetSum(Console.ReadLine()));
}
public static int GetSum(string num){
int summ = 0;
for(int i=0; i < num.Length; i++){
int currentNum;
if(int.TryParse(num[i].ToString(),out currentNum)){
if(currentNum % 2 == 1){
summ += currentNum;
}
}
}
return summ;
}
}
The simplest and easiest way would be using loops to find sum of digits.
int sum = 0;
int n = 1234;
while(n > 0)
{
sum += n%10;
n /= 10;
}
#include <stdio.h>
int main (void) {
int sum = 0;
int n;
printf("Enter ir num ");
scanf("%i", &n);
while (n > 0) {
sum += n % 10;
n /= 10;
}
printf("Sum of digits is %i\n", sum);
return 0;
}
Surprised nobody considered the Substring method. Don't know whether its more efficient or not. For anyone who knows how to use this method, its quite intuitive for cases like this.
string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();

Categories