浮动值转换为char

时间:2016-10-10 19:22:17

标签: c casting

在下面的代码中,

import subprocess
import random


def makeDir():
    tempDir = random.randrange(111111,999999)
    subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)])
    return tempDir

def mountShare(hostname, username, password):
    mountDir = makeDir()
    try:
        subprocess.Popen(["mount","-t","cifs", "-o",
                      "username="+username+",password="+password,
                      "//"+hostname+"/c$",
                      "/mntDir/"+mountDir])
    except:
        print("Mounting failed")

public static void main(String[] args) { Scanner s = new Scanner(System.in); double[] numbers = new double[9]; System.out.print("Enter 10 numbers: "); for (int i = 0; i < 10; i++){ double number = s.nextDouble(); } System.out.println("The mean is " + mean(numbers)); System.out.println("The standard deviation is : " + deviation(numbers)); } public static double deviation(double[] x) { double mean = mean(x); double squareSum = 0; for (int i = 0; i < x.length; i++) { squareSum += Math.pow(x[i] - mean, 2); } return Math.sqrt((squareSum) / (x.length - 1)); } public static double mean(double[] x) { double sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i]; } return sum / x.length; } } 存储在内存中的IEEE 754表示中,#include<stdio.h> int main(){ char array[] = {'1', 2, 5.2}; char* my_pointer = array[2]; printf("%c", *my_pointer); } 从此浮点表示中选取8位(第一个),这是由于小端格式。

C是一种松散类型的语言。允许将5.2投射到char

为什么程序被核心倾销?

2 个答案:

答案 0 :(得分:1)

在您的程序中,将char *my_pointer = array[2];更改为char *my_pointer = &array[2];,因为指针应存储地址。

#include<stdio.h>
int main(){
  char array[] = {'1', 2, 45.2};
  char *my_pointer = &array[2];
  printf("%c", *my_pointer);
}

<强>输出:

- //NOTE: asci value of - is 45

正如@AnT在评论中提到的,当您将45.2转换为char类型时,编译器将生成加载45.2的代码,截断该值并将其存储在您的char变量为45,因此在您打印时,请输出-

答案 1 :(得分:1)

char* my_pointer = array[2];

错了。其RHS类型为char,而不是char*。在编译器中调高警告级别将帮助您识别这些问题。

使用gcc -Wall,我收到以下警告:

soc.c: In function ‘main’:
soc.c:4:23: warning: initialization makes pointer from integer without a cast
    char* my_pointer = array[2];

之后,程序有未定义的行为。

您需要的是:

char* my_pointer = &array[2];

char* my_pointer = array + 2;