为什么Visual Studio编译器说我的C++函数中缺少分号?

Why is the Visual Studio compiler saying I'm missing a semicolon in my C++ function?

本文关键字:函数 C++ Studio Visual 编译器 我的 为什么      更新时间:2023-10-16

这是我的函数。width和height变量是在函数上面定义的全局整型变量,其值以百位为单位。

#define ORIGINAL_WIDTH 800;
#define ORIGINAL_HEIGHT 700;
void set_perspective(void) {
  int view_width, view_height;
  if (width < height) {
    view_width = width;
    view_height = (float) width * ORIGINAL_HEIGHT / ORIGINAL_WIDTH;
  }
  else {
    view_width = (float) height * ORIGINAL_WIDTH / ORIGINAL_HEIGHT;
    view_height = height;
  }
}

我的c++编译器注意到"error C2143: syntax error:在'/'之前缺少';' "

view_height = (float) width * ORIGINAL_HEIGHT / ORIGINAL_WIDTH;
and 
view_width = (float) height * ORIGINAL_WIDTH / ORIGINAL_HEIGHT;

这和类型转换有关吗?为什么我少了一个分号?感谢您的宝贵时间。

这是因为您的#define中有分号。它应该是这样的:

#define ORIGINAL_WIDTH 800
#define ORIGINAL_HEIGHT 700

#define执行文本替换,因此在编译器看来,您的行是这样的:

view_height = (float) width * 800;/700;;

避免使用宏(它们是文本替换)并使用常量,这样就不会出现这个问题。

static const int ORIGINAL_HEIGHT = 800;
static const int ORIGINAL_WIDTH = 700;