The following if
statement is only working properly if my digitToFind
variable is 5
, otherwise it gets ignored.
if(digitToFind == R)
digitToFindFreq = digitToFindFreq + 1;
end
The program is meant to count the number of digits in a given integer, and find the frequency of one specific number chosen by the user.
Example: 123445; number of digits is 6, frequency of 4 is 2.
digitToFindFreq = 0;
numOfDigits = 0;
integerInput = input('Enter an integer: ');
while(integerInput ~= round(integerInput))
fprintf('Invalid input. Try again!\n');
integerInput = input('Enter an integer: ');
end
digitToFind = input('Enter a digit number to find (0 to 9): ');
while(digitToFind < 0 || digitToFind > 9 || digitToFind ~= round(digitToFind))
fprintf('Invalid input. Try again!\n');
digitToFind = input('Enter a digit number to find (0 to 9): ');
end
if(integerInput == 0 && digitToFind ~= 0)
numOfDigits = 1;
digitToFindFreq = 0;
elseif(integerInput == 0 && digitToFind == 0)
numOfDigits = 1;
digitToFindFreq = 1;
end
while(integerInput >= 1)
integerInput = integerInput/10;
X = integerInput - fix(integerInput);
R = 10*X;
if(digitToFind == R)
digitToFindFreq = digitToFindFreq + 1;
end
integerInput = integerInput - X;
numOfDigits = numOfDigits + 1;
end
fprintf('\nNumber of digits: %d, Digit to find frequency: %d\n',numOfDigits,digitToFindFreq);
I have never had an issue like this before. It must be something small that I am missing because otherwise the program works properly.