大佬求助,运行的代码不是自己想要的怎么办?

2201_75489849 2024-02-08 19:35:47

代码是这样的,但是从11行scanf开始后面就显示不出来了。。。。。 

 

 

 

 

...全文
3815 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

计算letters:

 int i=0;
    while (name[i]!='\0')
    {
        letters++;
        i++;
    }

  • 打赏
  • 举报
回复 1

name的数据类型声明不对,不应该是char,应该是字符数组。
把第8行改为:
char name[10];
数组元素个数设置为允许接收的最大字符数,我举的例子是10。

tyz_C 02-08
  • 打赏
  • 举报
回复 1

抽空给你写的新版


#include <stdio.h>
#include <string>
#include <iostream>

#define DENSITY 62.4
using namespace std;
int main() {
    float weight, volume;
    int name_length = 0;
    string name;
    char c;

    printf("Hi! what's your first name?\n");
    getline(cin, name);
    for (char i: name)
        if (i != ' ') name_length++;
    printf("%s, what's your weight in pounds? \n", name.c_str());
    scanf("%f", &weight);
    for (char i: name) {
        c = name[i];
        if ((c < 48 || c > 57 )&& c != 46) {
            printf("Sorry %s, please enter the correct digit.\n", name.c_str());
            return 0;
        }
    }
    volume = weight / DENSITY;
    printf("well,%s,your volume is %2.2f cubic feet.n", name.c_str(), volume);
    printf("Also,your first name has %d letters, \n", name_length);
    printf("and we have %lu bytes to store it.\n", sizeof(name));
    getchar();
    return 0;
}
tyz_C 02-08
  • 打赏
  • 举报
回复

而且名字可能会有空格,所以在这里scanf()函数可能不太合适

tyz_C 02-08
  • 打赏
  • 举报
回复

我建议你定义一个string类型的来存名字,因为大多数名字是有多个字的

tyz_C 02-08
  • 打赏
  • 举报
回复

我给你的代码更改了一下


#include <stdio.h>
#include <string.h>
#define DENSITY 62.4
using namespace std;
int main() {
    float weight, volume;

    int size, letters;

    char name;

    printf("Hi! what's your first name?\n");
    scanf("%s", &name);
    printf("%c, what's your weight in pounds? \n", name);
    scanf("%f", &weight);
    size = sizeof(name);
    volume = weight / DENSITY;

    printf("well,%c,your volume is %2.2f cubic feet.n",name, volume);
    printf("Also,your first name has %d letters, \n", letters);
    printf("and we have %d bytes to store it.\n", size);
    getchar();
    return 0;
}

69,512

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧