gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:18 24 4
gpt4 key购买 nike

我在分配变量 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 使分子的数据类型为 double。

关于C 数学方程只正确分配一个变量一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com