名字不会出现在我的程序的底部部分

Name wont appear in the bottom part of my program

本文关键字:程序 底部 我的      更新时间:2023-10-16

这个程序用于我的分配,但程序的底部部分没有显示输入的名称,为什么?你们可以在Dev++中测试一下,看看它是如何工作的。

#include<stdio.h>
int main(){
    char n4m3[100],Pos;
    int rt,hr,gI,T,td,ss=100,pi=100,hc=100,NetIn;
    printf("    ==Employee Salary==");
    printf("n Name:");
    scanf(" %s",&n4m3);
    printf("n -Position- n  C-CEOn  V-VPn  S-Supervisorn  T-Team Leader");
    printf("n Postion:");
    scanf(" %s",&Pos);
    if (Pos=='C'||Pos=='c')
        {
            rt=500;
            printf("n  CEO Rate:500");
        }
        else if (Pos=='V'||Pos=='v')
        {
            rt=400;
            printf("n  VP Rate:400");
        }
        else if (Pos=='S'||Pos=='s')
        {
            rt=300;
            printf("n  Supervisor Rate:300");
        }
        else if (Pos=='T'||Pos=='t')
        {
            rt=200;
            printf("n  Team Leader Rate:200");
        }
    else printf("   Invalid Input");
    printf("n  Number of Hours Worked:");
    scanf("%d",&hr);
    printf("n  ==Summary==");
    gI=rt*hr;
    printf("n Gross Income:%d",gI);
    if (gI>=4000)
        T=gI*.4;
    else if (gI>=3000)
        T=gI*.3;
    else if (gI>=2000)
        T=gI*.2;
    else if (gI>=1000)
        T=gI*.1;
        printf("n Tax:%d",T);
        td=T+ss+pi+hc;
        printf("n Total Deductions:%d",td);
        NetIn=gI-td;
        printf("n Net Income is %d",NetIn);
        printf("n----------------------");
        printf("n Mr./Ms. %s your net income is %d",n4m3,NetIn);
}

这部分应该显示用户的姓名和净收入,但它没有显示姓名

它不工作,因为scanf想要一个char *,而你正在传递一个char (*)[100]。要解决这个问题,请记住,数组是一个连续的内存块,数组的名称是指向该内存开始的指针。因此,n4m3已经是一个char *,不需要把它的地址和&取走。

行应该是scanf(" %s",n4m3); //no '&'

相关笔记

我是在启用警告的情况下编译代码时发现这个问题的。你应该总是这样做!在Linux或Mac上使用clang标志-Wall -Wextra -pedantic进行编译会对这段代码产生几个警告。相关的是:

tmp.cpp:9:13: error: format specifies type 'char *' but the argument has type
  'char (*)[100]' [-Werror,-Wformat]
scanf(" %s",&n4m3);
        ~~  ^~~~~

谷歌错误带我到这里,这解决了问题。另一个警告是:

tmp.cpp:51:10: error: variable 'T' is used uninitialized whenever 'if' condition
      is false [-Werror,-Wsometimes-uninitialized]
else if (gI>=1000)
         ^~~~~~~~
tmp.cpp:54:24: note: uninitialized use occurs here
    printf("n Tax:%d",T);
                       ^
tmp.cpp:51:6: note: remove the 'if' if its condition is always true
else if (gI>=1000)
     ^~~~~~~~~~~~~
tmp.cpp:5:15: note: initialize the variable 'T' to silence this warning
int rt,hr,gI,T,td,ss=100,pi=100,hc=100,NetIn;
              ^
               = 0

有更多的警告,我将让你的编译器(一旦你设置正确)找到。在Windows上,通过使用这些说明来提高Visual Studio的警告级别。如果您让编译器为您分析代码,您将节省许多小时的工作。

当你输入一个没有空格的字符串时,它会工作得很好。但是如果你要输入一个带有空格的字符串,它的行为会改变,因为它只会读取字符串到空格。

你可以在你的代码中使用getline或fgets或sscanf来代替scanf .即

尝试替换行:

scanf(" %s",&n4m3);

fgets(n4m3,100,stdin);

工作正常。在程序结束后,带有result的命令行窗口关闭,因此您无法看到它。