C 数学方程只正确分配一个变量一次

C Math equation assigns a variable correctly only once

我在分配变量 global_duty 时遇到问题。等式中的所有其他变量每次都被赋值。据我所知,文本标签 duty_out_lab 至少重置了两次。我试过将 global_duty 声明为 intgintgdouble, 但似乎没有任何效果。第一次使用方程式时,它给出了正确的答案,然后每隔一次它只输出 0。一切都在没有任何警告的情况下编译。

这是相关代码。

#include <gtk/gtk.h>    
int global_ontime;
int global_offtime;
int global_duty;
GtkWidget *duty_out_lab;

static void 
set_duty ()
{
   global_duty = global_ontime / (global_ontime + global_offtime) * 100 ;  
   gchar *str = g_strdup_printf (" %d  percent ", global_duty);
   gtk_label_set_text (GTK_LABEL (duty_out_lab), str);
   g_free(str);
   printf ("On time is %d micro seconds\n", global_ontime);
   printf ("Off time is %d micro seconds\n", global_offtime);  
   printf ("Duty cycle is %d percent \n\n", global_duty);   
}

static void
set_ontime (GtkSpinButton *spinbutton, gpointer user_data)
{
   gint value1 = gtk_spin_button_get_value_as_int (spinbutton);
   global_ontime = value1;
   set_duty();
}

static void
set_offtime (GtkSpinButton *spinbutton, gpointer user_data)
{
   gint value2 = gtk_spin_button_get_value_as_int (spinbutton);
   global_offtime = value2;
   set_duty();
}

终端输出

On time is 1 micro seconds
Off time is 0 micro seconds
Duty cycle is 100 percent 

On time is 1 micro seconds
Off time is 1 micro seconds
Duty cycle is 0 percent 

On time is 1 micro seconds
Off time is 2 micro seconds
Duty cycle is 0 percent 

On time is 2 micro seconds
Off time is 2 micro seconds
Duty cycle is 0 percent 

gtk 输出

]2输出好

1输出不好

第一步:将变量 global_duty 声明为 float 或 double。

第二步:替换行

global_duty = global_ontime / (global_ontime + global_offtime) * 100 ;  

来自

global_duty = global_ontime * 1.0 / (global_ontime + global_offtime) * 100 ;  

在 C 中,2(一个整数)除以 5(一个整数)的结果是 0(一个整数),而不是 0.4(一个 float/double)。同样,在您的情况下,global_duty 的值被截断为 0。如果您想要小数值作为答案,请使用 'float' 或 'double' 数据类型。分子乘以 1.0 使分子的数据类型为双精度。