简体   繁体   中英

Why do i keep getting 0 as an output?

The point of the exercise is to delete every K number digit from a line of numbers between N and M. As an output I have to get the number of digits remaining in that line, I also don't have to print out said line. Here's the code:

#include <iostream>

using namespace std;

int main() {
  int n, m, k;
  int i = n;
  int a = 0;

  cin >> n >> m >> k;

  if (1 <= n && n < m && m < 1000 && 1 <= k && k < 1000) {
  } else {
    return 0;
  }

  while (i <= m - n) {
    i++;

    if (i < 10) {
      a++;
    } else if (i >= 10 && i < 100) {
      a += 1 * 2;
    } else if (i > 100) {
      a += 1 * 3;
    }
  }

  cout << a - a / k;

  return 0;
}
  int n, m, k;
  int i = n;

Local variables in C++ are uninitialized, so you don't know the values of n , m , and k . Setting i to n is meaningless here, as n has a uninitialized value we don't know, so i now has some uninitialized value we don't know.

You need to move the assignment of i until after you know the value of n .

  int n, m, k;
  cin >> n >> m >> k;`
  int i = n;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM