【问题标题】:Multiplying two variable names on mac os在mac os上将两个变量名相乘
【发布时间】:2012-05-07 18:17:05
【问题描述】:

我正在尝试让一个 c 程序在我的 mac 分区中运行,并且已经想出了大部分的方法,但无法解决一个非常简单的问题。

所以我有一个 .h 文件,我在其中声明了所有变量,并且在我的 .c 文件中我试图运行类似的命令

L2toL1 = (L2_transfer_time)*(L1_block_size);

但是我从来没有得到正确的答案。我在上面的行之前打印变量并且它们打印正确但是当它们相乘时的答案是遥遥无期。那么如何才能完成正确的乘法呢?

.h 文件看起来像

#define CONFIG_PARAM 16
#define HIT 1
#define MISS 0
#define TRUE 1
#define FALSE 0

unsigned long long L2=0;
unsigned long long L1=0;

int L1_block_size=0;
int L1_cache_size=0;
int L1_assoc=0;
int L1_hit_time=0;
int L1_miss_time=0;
int L2_block_size=0;
int L2_cache_size=0;
int L2_assoc=0;
int L2_hit_time=0;
extern int L2_miss_time=0;
int L2_transfer_time=0;
int L2_bus_width=0;
int mem_sendaddr=0;
int mem_ready=0;
int mem_chunktime=0;
int mem_chunksize=0;
unsigned long long test;

.c 文件然后运行以下内容并从配置文件中读取特定值 print f 语句的答案应该是 195,但应该是 49567

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "definitions.h"

int main(int argc, char *argv[]) {
    FILE *config_file, *trace;
    unsigned int address, exec_info;
    char check, trash[25], op;
    int j, para;
    int i=0;

    if(argc >= 2)   
    config_file = fopen(argv[1],"r");
    else 
    config_file = fopen("config0.txt","r");

// Grabs desired cache parameters from the specified config files
while(fscanf(config_file,"%s %d\n",trash,&para) == 2) {
config[i] = para;
i++;      
}

// Close the config file
fclose(config_file);

// Puts Cache parameters from config file in desired variables
InitializeParameters();

/*
unsigned long long L2toL1;
L2toL1 = (L2_miss_time)*(L1_block_size);
printf("L2toL1 is: %Lu\n",L2toL1);

}

int InitializeParameters() {   
L1_cache_size = config[0];
L1_block_size = config[1];
L1_assoc = config[2];
L1_hit_time = config[3];
L1_miss_time = config[4];
L2_block_size = config[5];
L2_cache_size = config[6];
L2_assoc = config[7];
L2_hit_time = config[8];
L2_miss_time = config[9];
L2_transfer_time = config[10];
L2_bus_width = config[11];
mem_sendaddr=config[12];
mem_ready=config[13];
mem_chunktime=config[14];
mem_chunksize=config[15];    
}

感谢您的帮助

【问题讨论】:

  • 输入是什么?你得到了什么输出?
  • 请展示一个完整的示例(包括所有变量的完整定义、打印语句以及您正在使用的值)。
  • 值是什么?你确定没有溢出吗?
  • 您的config 数组在两个地方使用,但未在任何地方定义?

标签: c macos gcc multiplication


【解决方案1】:

您可能会得到奇怪的数字,因为您的结果不适合目标变量。示例:您将两个数字相乘,这些数字太大而无法放入目标内存位置。

例如,如果你有这段代码:

#include <stdio.h>
int main(int argc, char **argv)
{
   int a, b, c;
   a = 2000000000;
   b = 2000000000;
   c = a*b;
   printf ("%d x %d = %d", a, b, c);
   return 0;
}

将打印:

 2000000000 x 2000000000 = -1651507200

话虽如此,在头文件中声明变量并不是一个好主意。

【讨论】:

  • 这不可能是被相乘的数字是 32 和 6
【解决方案2】:

您在 printf 格式字符串中使用了%Lu。我认为L 仅适用于long double 类型,不适用于long long int 类型。

你应该像这样使用%llu

printf("L2toL1 is: %llu\n",L2toL1);

当然,这取决于您使用的是什么 C 库:并非所有库都完全符合标准,您的可能使用其他库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多