c/app/vui_bmi.c · 2736 字节 · 下载原文
/* vui_bmi.c —— VUI 示例③:**BMI 计算器**(内联 XML,键盘输入 + 计算 + 回显)
* vui_bmi.c -- VUI example 3: a **BMI calculator** (inline XML, text input + math + output)
*
* 演示:多个 edit 控件、按钮读值计算、把结果写回 label;全部走消息队列(任意语言可复用)。
* Shows: several edit controls, a button that reads and computes, and writing the result back
* to a label; everything goes through the message queue (any language can do the same).
*/
#include <vml_vui.h>
#include <stdlib.h>
#include <string.h>
static const char* LAYOUT =
"<vui title=\"BMI\"><stack orientation=\"vertical\" spacing=\"12\" padding=\"16\"><label key=\"title\" text=\"BMI 计算器\" size=\"22\" bold=\"true\"/><edit key=\"h\" placeholder=\"身高(厘米)\"/><edit key=\"w\" placeholder=\"体重(公斤)\"/><button key=\"go\" text=\"计算\"/><label key=\"out\" text=\"填好上面两项,点计算\" size=\"18\"/></stack></vui>";
/* 整数 → 文本(BMI 用十分位:bmi10 = 245 表示 24.5)。 */
/* Integer -> text (BMI in tenths: bmi10 = 245 means 24.5). */
static void put_bmi(char* dst, int bmi10) {
int whole = bmi10 / 10;
int frac = bmi10 % 10;
int n = 0;
char tmp[16];
if (whole == 0) { tmp[n] = '0'; n = n + 1; }
while (whole > 0) { tmp[n] = '0' + whole % 10; whole = whole / 10; n = n + 1; }
int i;
for (i = 0; i < n; i++) dst[i] = tmp[n - 1 - i];
dst[n] = '.';
dst[n + 1] = '0' + frac;
dst[n + 2] = 0;
}
int main(void) {
int h;
int w;
int go;
int out;
int ev[3];
if (vui_layout_load_text((char*)LAYOUT) <= 0) return 1;
h = vui_find_view("h");
w = vui_find_view("w");
go = vui_find_view("go");
out = vui_find_view("out");
for (;;) {
int t = vui_wait_event(ev, 500);
if (t == VML_VUI_CLOSE) break;
if (t != VML_VUI_CLICK || ev[1] != go) continue;
char hs[32];
char ws[32];
char msg[96];
vui_get_text(h, hs, 32);
vui_get_text(w, ws, 32);
int hcm = atoi(hs);
int wkg = atoi(ws);
if (hcm <= 0 || wkg <= 0) {
vui_set_text(out, "请输入有效的身高和体重");
continue;
}
/* bmi10 = wkg * 100000 / (hcm*hcm) —— 纯整数,结果 = 245 表示 24.5(十分位)。 */
int bmi10 = (wkg * 100000) / (hcm * hcm);
strcpy(msg, "BMI = ");
int len = strlen(msg);
put_bmi(msg + len, bmi10);
strcat(msg, bmi10 < 185 ? "(偏瘦)" : (bmi10 < 240 ? "(正常)" : (bmi10 < 280 ? "(偏胖)" : "(肥胖)")));
vui_set_text(out, msg);
}
vui_layout_close();
return 0;
}