不受控制的循环和函数 C++跳过

Uncontrolled looping and function Skipping in C++?

本文关键字:函数 C++ 跳过 循环 受控制      更新时间:2023-10-16

我正在尝试从键盘读取两个用户输入的数字到发现板上。我有代码用于读取第一个数字,但由于某种原因,当它点击相同的键盘((;函数第二次它似乎没有调用函数以允许输入,而是跳过扫描并打印其下方的行,如果您按下按钮重新开始,程序拾取的地方是随机的,任何可能导致这种情况的想法。我正在在线 Ide 上编译。下面是代码。

#include <iostream>
#include "mbed.h"
DigitalIn columns[3] = {PB_6, PB_7, PD_0};  // Columns for digital input
DigitalOut rows[4] = {PA_5, PA_1, PA_2, PA_3};  // rows for digital output
DigitalIn startButton(USER_BUTTON);
DigitalOut led1(LED1);  // reference LED
int numpad[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {-2, 0, -1}};  // keypad
int Total();
int Keypad();
int c = 0;
int Read;
int Num1 = 0;
int SelectOp();
int Oper;
int main() {
  while (1) {
    if (startButton == 1) {
      printf("%snrInput First Numbernr");
      wait(.5);
      Keypad();
      int First = Num1;
      Num1 = 0;
      printf("%snr Your first number is ");
      printf("%i", First);
      printf("%snr Input your second numbernr");
      wait(.5);
      Keypad();  // this seems to be getting skipped
      int Second = Num1;
      Num1 = 0;
      printf("%snr Your Second number is ");
      printf("%i", Second);
      printf("%snrSelect Operator: 1(+), 2(-), 3(*), 4(/)");
      Keypad();
      Oper = Num1;
    }
  }
}
int Keypad() {
  columns[0].mode(PullUp);
  columns[1].mode(PullUp);
  columns[2].mode(PullUp);
  while (1) {
    if (Read == -1) {
      return Num1;
    }
    for (int i = 0; i < 4; i++) {
      rows[0] = 1;
      rows[1] = 1;
      rows[2] = 1;
      rows[3] = 1;
      rows[i] = 0;
      wait(0.01);
      for (int j = 0; j < 3; j++) {
        if (columns[j] == 0) {
          Read = numpad[i][j];
          Total();
          c++;
          if (c == 5) {
            c = 0;
          }
          wait(0.005);
          while (columns[j] == 0)
            ;
        }
      }
    }
  }
}
int Total() {
  if (Read >= 0) {
    Num1 *= 10;
    Num1 += Read;
    printf("%inr", Num1);
  } else {
    return Num1;
  }
  return Num1;
}

Read 在通过 Keypad(( 的第一个循环中设置为 -1 时,当您再次输入 Keypad() 时它仍然是 -1,从而立即返回。

使用一些空间来呼应@Scheff根据变量的预期生存期确定变量范围的重要性,从而尽可能最小化全局变量。